PIVOT操作

时间:2014-09-03 13:16:57

标签: sql sql-server sql-server-2008 tsql pivot

name      roll                  vote  total vote        status

aaa     Administrator             1    2            Feedback Received
aaa     HR Support Staff          1    2            Feedback Received
dev     Administrator             1    2            Shortlisted
dev     HR Support Staff          1    2            Shortlisted
raj     Administrator             1    1            Feedback Received
rajesh  HR Support Staff          2    2            Shortlisted

需要显示

Name     HR Support Staff       Administrator    Total Vote       Status

aaa            1                    1               2           Feedback Recived  

如何在这种方法中显示?

2 个答案:

答案 0 :(得分:1)

这是PIVOT方法:

select [name], [Administrator], [HR Support Staff], [total vote], [status]
from Table1
pivot (
  min([vote])
  for [roll] in ([Administrator], [HR Support Staff])
) p

<强> Working SqlFiddle

答案 1 :(得分:0)

这里的细节非常稀少。您可以使用PIVOT,也可以使用交叉表。如果值是静态的,这是使用交叉表可以实现此目的的一种方法。

select name
    , SUM(case when roll = 'HR Support Staff' then 1 end) as HRSupportStaff
    , SUM(case when roll = 'Administrator' then 1 end) as Administrator
    , MAX(TotalVote) as TotalVote
    , Status
from YourTable
group by name, Status