SQL将一列的计数分开

时间:2016-01-18 14:17:55

标签: sql database count

我有一个包含三列的SQL表:

userId
userName
item

我创建了这个SQL查询,它将计算一个用户的所有项类型:

 select 
     count(ItemID) as 'count of all items types', 
     userId,
     userName
 from 
     userTable
 where 
     ItemID in (2, 3, 4)
     and userId = 1
 group by 
     userId, userName

结果如下:

+--------+----------+--------------------------+
| userId | userName | count of all items types |
+--------+----------+--------------------------+
|  1     | kim      |     25                   |

我正在寻找一种分离迭代类型计数的方法,所以结果应该是这样的:

+--------+----------+----------------+----------------+-----------------+
| userId | userName | count of item1 | count of item2 |  count of item3 |
+--------+----------+----------------+----------------+-----------------+
|  1     | kim      |     10         |       10       |   5             |

3 个答案:

答案 0 :(得分:3)

SELECT
    userID,
    userName,
    SUM(CASE WHEN ItemID = 2 THEN 1 ELSE 0 END) AS count_of_item1,
    SUM(CASE WHEN ItemID = 3 THEN 1 ELSE 0 END) AS count_of_item2,
    SUM(CASE WHEN ItemID = 4 THEN 1 ELSE 0 END) AS count_of_item3
FROM
    My_Table
GROUP BY
    userID,
    userName

答案 1 :(得分:2)

这称为条件聚合。请使用CASE。

使用COUNT:

select 
  count(case when ItemID = 1 then 1 end) as count_item1, 
  count(case when ItemID = 2 then 1 end) as count_item2, 
  count(case when ItemID = 3 then 1 end) as count_item3 
...

then 1也可以是除null之外的任何其他内容,例如then 'count me'。这是有效的,因为COUNT计算非空值并且省略{{1}中的ELSE你得到null。你也可以明确地添加CASE WHEN。)

或使用SUM:

else null

答案 2 :(得分:0)

这就是你要做的:

select userId,
           username,
           SUM(CASE WHEN ItemID = '2' THEN 1 ELSE 0 END) AS Item2-Cnt,
           SUM(CASE WHEN ItemID = '3' THEN 1 ELSE 0 END) AS Item3-Cnt,
           SUM(CASE WHEN ItemID = '4' THEN 1 ELSE 0 END) AS Item4-Cnt
    FROM userTable
    GROUP BY userID, userName