我想询问有关汇总的mysql只获得汇总值,这是我的代码
SELECT tbldept.CodeDept AS Dept,
SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) AS headcount,
SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) * 144 AS RegHrsEst,
CONCAT(ROUND(20), '%') AS TargetOT,
round(SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) * 144 * 0.2) AS OTHrsBdgt
FROM tbldept
LEFT JOIN tblemp
ON tbldept.CodeDept = tblemp.CodeDept AND
tblemp.class = "DIR"
WHERE tbldept.CodeDept != 'FIN' AND
tbldept.CodeDept != 'HRT' AND
tbldept.CodeDept != 'ISD'
GROUP BY tbldept.CodeDept with ROLLUP;
汇总查询的结果:
我怎样才能获得汇总值?先谢谢
答案 0 :(得分:2)
如果您只想要rollup
行,只需使用having
:
SELECT tbldept.CodeDept AS Dept,
SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) AS headcount,
SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) * 144 AS RegHrsEst,
CONCAT(ROUND(20), '%') AS TargetOT,
round(SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) * 144 * 0.2) AS OTHrsBdgt
FROM tbldept
LEFT JOIN tblemp
ON tbldept.CodeDept = tblemp.CodeDept AND
tblemp.class = "DIR"
WHERE tbldept.CodeDept != 'FIN' AND
tbldept.CodeDept != 'HRT' AND
tbldept.CodeDept != 'ISD'
GROUP BY tbldept.CodeDept with ROLLUP
HAVING Dept IS NULL;
having
应该有效,检查是否存在其他原因。
或者只使用子查询包装查询:
SELECT *
FROM (
SELECT tbldept.CodeDept AS Dept,
SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) AS headcount,
SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) * 144 AS RegHrsEst,
CONCAT(ROUND(20), '%') AS TargetOT,
round(SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) * 144 * 0.2) AS OTHrsBdgt
FROM tbldept
LEFT JOIN tblemp
ON tbldept.CodeDept = tblemp.CodeDept AND
tblemp.class = "DIR"
WHERE tbldept.CodeDept != 'FIN' AND
tbldept.CodeDept != 'HRT' AND
tbldept.CodeDept != 'ISD'
GROUP BY tbldept.CodeDept with ROLLUP
) t
WHERE Dept IS NULL;