日期:2014-05-17  浏览次数:20576 次

这个数据语句怎么写?
name            number
王               -3
王               -4
王               -3
王               1
夏               -2
夏               2
夏               -1
夏               2


输出结果为
name            count_1(正值的次数)  count_2(负值的次数)   正负比
王              1                      3                       0.33
夏              2                      2                       1
上面的输出sql语句如何写?

------解决方案--------------------
use Tempdb
go
--> --> 
 
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([name] nvarchar(1),[number] int)
Insert #T
select N'王',-3 union all
select N'王',-4 union all
select N'王',-3 union all
select N'王',1 union all
select N'夏',-2 union all
select N'夏',2 union all
select N'夏',-1 union all
select N'夏',2
Go
Select [name],
[count_1]=sum(case when [number]>=0 then 1 else 0 end),
[count_2]=sum(case when [number]<0 then 1 else 0 end),
[正负比]=
str(case when count(*)=count(case when [number]>=0 then 1 end)then 1 else count(case when [number]>=0 then 1 end) end *1.0/case when count(case when [number]<0 then 1  end)=count(*) then 1 else count(case when [number]<0 then 1  end) end,5,2)
from #T
group by [name]
/*
王 1 3  0.33
夏 2 2  1.00
*/

------解决方案--------------------

--引用1楼大版的数据
select [name],[count_1],[count_2],[count_1]*(case when[count_2]=0 then 0 else 1.0/[count_2] end)
from ( Select [name],[count_1]=sum(case when [number]>=0 then 1 else 0 end),
[count_2]=sum(case when [number]<0 then 1 else 0 end)
from #T group by [name] ) as a