欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

最小公约数

程序员文章站 2022-04-19 15:09:39
...

[摘要]一个朋友在展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 
二、测试
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%t20 and dbo.GetMaxgongyue(t1,t2)=1 then CAST(t1 as NCHAR(4))+'/'+ CAST(t2 as NCHAR(4)) 
     when t1%t20 and dbo.GetMaxgongyue(t1,t2)1 then CAST(t1/dbo.GetMaxgongyue(t1,t2) as NCHAR(4))+'/'+ 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