如何在sql server 2008中的单个查询中执行两个分组

时间:2014-05-08 13:34:42

标签: sql sql-server sql-server-2008 case

我有一个包含三列Stud_Name,Operated_By,Status

的表
Stud_Name   Operated_By      Status
  Sri            1               Aprove
  Manoj          1               Aprove
 Ranjan          1               Rejected
  Arif           3               Rejected

我想要以下结果:

Operated_By    Aprove   Rejected
   1            2          1
   3            0          1

提前致谢

1 个答案:

答案 0 :(得分:4)

SQL Fiddle

SELECT Operated_By,
       SUM(CASE WHEN Status = 'Aprove' THEN 1 ELSE 0 END) AS Aprove,
       SUM(CASE WHEN Status = 'Rejected' THEN 1 ELSE 0 END) AS Rejected
FROM MyTable
GROUP BY Operated_By