日期:2014-05-17 浏览次数:20624 次
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