SQL 比例问题
例如表A
a_1 a_2
3 2
4 6
7 8
求
a_1 :a_2
3:2
2:3
7:8
要约分
[解决办法]
create table taba(a_1 int, a_2 int)insert into tabaselect 3, 2 union allselect 4, 6 union allselect 7, 8create function fnyf(@a1 int,@a2 int)returns varchar(15)asbegin declare @m int,@i int,@b1 int,@b2 int select @m=case when @a1>=@a2 then @a2 else @a1 end,@i=2,@b1=@a1,@b2=@a2 while(@i<=@m) begin if @b1%@i=0 and @b2%@i=0 select @b1=@b1/@i,@b2=@b2/@i select @i=@i+1 end return cast(@b1 as varchar)+':'+cast(@b2 as varchar)endselect dbo.fnyf(a_1,a_2) 'a_1:a_2' from tabaa_1:a_2---------------3:22:37:8(3 row(s) affected)
[解决办法]
--> 测试数据: @表Adeclare @表A table (a_1 int,a_2 int)insert into @表Aselect 3,2 union allselect 12,18 union all --改成12和18 测试约分select 7,8declare @i int,@j intselect @i=max(a_1),@j=max(a_2) from @表A;with maco as (select number from master..spt_values where type='p' and (number between 2 and @i or number between 2 and @j))select isnull(b.c1,a.a_1) as a_1,isnull(b.c2,a.a_2) as a_2 from @表A aleft join (select min(a_1/number) as c1,min(a_2/number) as c2,a_1,a_2 from maco a,@表A b where a_1%number=0 and a_2%number=0 group by a_1,a_2)bon a.a_1=b.a_1 and a.a_2=b.a_2/*a_1 a_2----------- -----------3 22 37 8*/