2016-02-20 81 views
0

我正在生成數據集UNION三個數據集。然後,我想在數據集的末尾添加一行summary,僅用於一列。添加摘要列

數據:

id uid type seen 
1 20 A  1 
2 20 B  1 
3 20 C  1 
4 6 A  1 
5 1 A  1 
6 3 A  0 
7 6 A  0 
8 1 B  0 

查詢:

SELECT * FROM 
(
    (SELECT 
      type, 
      GROUP_CONCAT(DISTINCT uid) AS users, 
      COUNT(type) AS typeCount, 
      MIN(seen) as seen 
    FROM `test2` 
    WHERE type = 'A' 
    GROUP BY type) 

    UNION 

    (SELECT 
      type, 
      GROUP_CONCAT(DISTINCT uid) AS users, 
      COUNT(type) AS typeCount, 
      MIN(seen) as seen 
    FROM `test2` 
    WHERE type = 'B' 
    GROUP BY type) 

    UNION 

    (SELECT 
      type, 
      GROUP_CONCAT(DISTINCT uid) AS users, 
      COUNT(type) AS typeCount, 
      MIN(seen) as seen 
    FROM `test2` 
    WHERE type = 'C' 
    GROUP BY type) 
) as result 

查詢結果:

id uid   type seen 
A 20,6,1,3 5  0 
B 20,1  2  0 
C 20   1  1 

個預期結果:

id  uid   type seen 
A  20,6,1,3 5  0 
B  20,1  2  0 
C  20   1  1 
total      2  -- counting `0` here 

PS:我知道查詢可以通過只使用GROUP BY被簡化,但它不是真實的情景,這是問題的只是最低限度的解釋。

+0

你確定你需要'UNION'不'UNION ALL'? – Susilo

+0

是的,我不想複製 – Shaharyar

+0

對於羣組,我們可以做一些彙總http://dev.mysql.com/doc/refman/5.7/en/group-by-modifiers.html然而,你有問題的查詢如果你提供更多的信息和邏輯,你可以簡化很多。也許是一些正確的樣本數據和預期的結果。 –

回答

2

您可以在query..just適用ROLLUP留下您的子查詢如知道對不對,然後對他們的申請GROUP BY

SELECT type, MIN(users) users, MIN(typeCount) typeCount, MIN(seen) seen, IF(seen=0,1,0) zero_seen FROM 
(

    -- previous sub query 

) as result 
GROUP BY type WITH ROLLUP 

編輯: ROLLUP只做總和或計算總計,做計數IF(seen=0,1,0) zero_seen加入計數0見過..

+0

但我只想計算'0'。我也可以使用匯總,你可以在這個查詢上應用匯總? – Shaharyar

+0

是的,你可以...我可以...等一秒鐘,而我更新的答案.. – Susilo