mysql 获取汇总值

mysql get rollup value

我想问一下 mysql rollup 只获取 rollup 值,这是我的代码

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;

汇总查询结果:

我怎样才能只获得汇总值?先谢谢了

如果您只想要 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;