选择SQL查询

时间:2015-04-15 12:05:56

标签: sql

我有一个表Table1,其数据如下:

User    Department       Location      Jan        Feb              
-----------------------------------------------------
P1        Admin          IND           1          0
P2        Admin          IND           1          1
P3        Admin          US            0          1
P1        HR             UK            1          0
P2        HR             UK            0          1
P1       Admin           AUS           1          1
P1       Admin           AUS           1          0

我需要从这个表中获取数据,如:

Department            Jan                     Feb
-------------------------------------------------
Admin                 2                       3
HR                    1                       1

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:2)

假设" 2 3"是一个拼写错误,你实际上是指管理员是" 4 3",查询是:

SELECT Department,
    COUNT(CASE WHEN Jan = 1 THEN 1 END) AS Jan,
    COUNT(CASE WHEN Feb = 1 THEN 1 END) AS Feb
FROM Table1
GROUP BY Department;