我需要在每个月的结果后添加行Total,例如:
Month ID Mod1 Mod2 Mod3
2014/1 1 5 4 2
2014/1 2 1 5 3
Total 6 9 5
2014/2 3 6 3 2
2014/2 4 2 1 4
Total 8 4 6
这是我的查询,没有行Total:
SELECT
id_user,
month,
year,
SUM(IF(mod = 1, 1, 0)) AS mod_1,
SUM(IF(mod = 2, 1, 0)) AS mod_2,
SUM(IF(mod = 3, 1, 0)) AS mod_3
FROM
DW_RM_Log
WHERE
year = 2014
GROUP BY
year, month, id_user
ORDER BY
year, month
我如何在mySQL中执行此操作?
答案 0 :(得分:0)
您可以使用GROUP BY查询WITH ROLLUPS:
SELECT
CASE WHEN id_user IS NOT NULL THEN CONCAT(`year`, '/', `Month`)
ELSE 'Total' END AS `Year_Month`,
id_user,
SUM(IF(`mod` = 1, 1, 0)) AS mod_1,
SUM(IF(`mod` = 2, 1, 0)) AS mod_2,
SUM(IF(`mod` = 3, 1, 0)) AS mod_3
FROM
DW_RM_Log
WHERE
`year` = 2014
GROUP BY
`year`, `month`, id_user
WITH ROLLUP
HAVING `year` IS NOT NULL AND `month` IS NOT NULL
请参阅小提琴here。