2016-01-18 73 views
0

我有一個包含三列的SQL表: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     | 

,我正在尋找一種方式來itemes類型的計數分開,所以結果應該爲L ike this:

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

回答

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 
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也可以是任何東西,除了空,如then 'count me'否則這工作,因爲COUNT計數非空值和CASE WHEN省略ELSE當你空你也可以。明確添加else null

或用SUM:

select 
    sum(case when ItemID = 1 then 1 else 0 end) as count_item1, 
    sum(case when ItemID = 2 then 1 else 0 end) as count_item2, 
    sum(case when ItemID = 3 then 1 else 0 end) as count_item3 
... 
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