当前位置: 代码迷 >> Sql Server >> SQL 比例有关问题
  详细解决方案

SQL 比例有关问题

热度:34   发布时间:2016-04-27 13:02:45.0
SQL 比例问题
例如表A
a_1 a_2
3 2
4 6
7 8


求 
a_1 :a_2 
3:2
2:3
7:8


要约分  
 

------解决方案--------------------
SQL code
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>[email protected] then @a2 else @a1 end,@i=2,@[email protected],@[email protected] while(@i<[email protected]) begin   if @[email protected]=0 and @[email protected]=0     select @[email protected][email protected],@[email protected][email protected]   select @[email protected]+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)
------解决方案--------------------
SQL code
--> 测试数据: @表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*/
  相关解决方案