添加摘要行

时间:2016-02-20 08:04:32

标签: mysql sql

我正在通过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即可简化查询,但这不是真实情况,只是对问题的最小解释。

1 个答案:

答案 0 :(得分:2)

您可以在查询中应用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看出..