在1个查询中获得多个COUNT

时间:2014-02-07 00:54:42

标签: sql count

    id    name    type
---------------------
    1     a        ir
    2     b        sr
    3     a        ir
    4     a        sr
    5     b        ir

我想在SQL中使用COUNT这样的输出

name  ir   sr
-------------
a     2     1
b     1     1

1 个答案:

答案 0 :(得分:0)

SELECT name,
       SUM(CASE type WHEN 'ir' THEN 1 ELSE 0 END) AS ir,
       SUM(CASE type WHEN 'sr' THEN 1 ELSE 0 END) AS sr
FROM YourTable
GROUP BY name

在MySQL中,您可以将其简化为:

SELECT name,
       SUM(type = 'ir') AS ir,
       SUM(type = 'sr') AS sr
FROM YourTable
GROUP BY name