我正在生成數據集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
被簡化,但它不是真實的情景,這是問題的只是最低限度的解釋。
你確定你需要'UNION'不'UNION ALL'? – Susilo
是的,我不想複製 – Shaharyar
對於羣組,我們可以做一些彙總http://dev.mysql.com/doc/refman/5.7/en/group-by-modifiers.html然而,你有問題的查詢如果你提供更多的信息和邏輯,你可以簡化很多。也許是一些正確的樣本數據和預期的結果。 –