日期:2014-05-18  浏览次数:20417 次

Group BY
Name Date Des

jason 2010-11-10 yes
barry 2010-11-12 yes
barry 2010-11-10 no
barry 2010-11-12 yes
jason 2010-11-10 yes
jason 2010-11-12 no


  显示结果:

  yes no
jason 2010-11-10 2 0
jason 2010-11-12 0 1 
barry 2010-11-10 0 1
barry 2010-11-12 2 0  


用Group by 如何做到这种显示效果

------解决方案--------------------
SQL code
use Tempdb
go
--> --> 
 
if not object_id(N'Tempdb..#T') is null
    drop table #T
Go
Create table #T([Name] nvarchar(5),[Date] Datetime,[Des] nvarchar(3))
Insert #T
select N'jason','2010-11-10',N'yes' union all
select N'barry','2010-11-12',N'yes' union all
select N'barry','2010-11-10',N'no' union all
select N'barry','2010-11-12',N'yes' union all
select N'jason','2010-11-10',N'yes' union all
select N'jason','2010-11-12',N'no'
Go
Select 
[Name],
sum(CASE WHEN  [Des]='yes' THEN 1 ELSE 0 END) AS yes,
sum(CASE WHEN  [Des]='no' THEN 1 ELSE 0 END) AS [no]
from #T 
GROUP BY [Name],[Date]
ORDER BY 1,2

/*
Name    yes    no
barry    0    1
barry    2    0
jason    0    1
jason    2    0
*/