>  기사  >  데이터 베이스  >  最小公约数

最小公约数

WBOY
WBOY원래의
2016-06-07 15:57:101274검색

[摘要]一个朋友在展BOM的时候有这样的需求,两列字段(数值):A ,B A=用量,B=底数,组成用量=用量/底数。A/B,若能被整除,显示整除的结果,若不能整除显示分数形式A/B(分数形式要是约分后的格式)3/6=1/3。 我的思路: 1.SQL取余判断是否能被整除 2.撰

[摘要]一个朋友在展BOM的时候有这样的需求,两列字段(数值):A ,B A=用量,B=底数,组成用量=用量/底数。A/B,若能被整除,显示整除的结果,若不能整除显示分数形式A/B(分数形式要是约分后的格式)3/6=1/3。

我的思路:

1.SQL取余判断是否能被整除

2.撰写两个整形数值的最大公约数,然后分子与分母分别除以最大公约数。

其中进行转换化成字符串格式。

一、自定义最大公约数函数:

Create FUNCTION [dbo].[GetMaxgongyue]
(
	@num1   int ,
	@num2  int 
)
RETURNS  int
as 
begin
DECLARE @times INT 
DECLARE @min INT 
DECLARE @result BIGINT 

IF( @num1 >= @num2 ) 
  SET @min=@num2 
ELSE 
  SET @min=@num1 

SET @times=@min 

WHILE(@times <= @min ) 
  BEGIN 
      IF( @num1%@times = 0 
          AND @num2%@times = 0 ) 
        BEGIN 
            SET @result=@times 

            BREAK 
        END 

      SET @times=@times - 1 
  END 

return @result
end
二、测试
drop table tt
Create table tt(t1  int,t2  int)
insert into  tt(t1 ,t2 )values(1,3)
insert into  tt(t1 ,t2 )values(2,4)
insert into  tt(t1 ,t2 )values(3,9)
insert into  tt(t1 ,t2 )values(6,3)
insert into  tt(t1 ,t2 )values(4,2)
insert into  tt(t1 ,t2 )values(2,331)
select t1,t2,t1%t2 取余,
case when t1%t2<>0 and dbo.GetMaxgongyue(t1,t2)=1 then CAST(t1 as NCHAR(4))+&#39;/&#39;+ CAST(t2 as NCHAR(4)) 
     when t1%t2<>0 and dbo.GetMaxgongyue(t1,t2)<>1 then CAST(t1/dbo.GetMaxgongyue(t1,t2) as NCHAR(4))+&#39;/&#39;+ CAST(t2/dbo.GetMaxgongyue(t1,t2) as NCHAR(4)) 
else cast(cast(t1/t2 as decimal(9,5)) as NCHAR(20)) end result
from tt
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.