比较同一查询中SUM(CASE ... END)的列

时间:2013-05-09 03:40:35

标签: mysql

我正在尝试向我的查询中添加一个名为Ready的列,检查Complete的总和是否为Total的总和,如果为真,则检查是否为'Y' 'N',如果为FALSE。

这是我的查询,可以生成4列

 SELECT pc.Sub,
    SUM(CASE WHEN `SheetStatus` LIKE 'Complete' THEN 1 ELSE 0 END) AS 'Complete',
    SUM(CASE WHEN `SheetStatus` LIKE 'Not started' THEN 1 ELSE 0 END) AS 'Not Started',
    SUM(CASE WHEN `CheckSheet` LIKE '%' THEN 1 ELSE 0 END) AS 'Total'        
FROM `pc`
Group By pc.Sub WITH ROLLUP

如果可能的话,我无法弄清楚如何创建额外的列。 此致

2 个答案:

答案 0 :(得分:1)

尝试外部SELECT

SELECT `Complete`, 
       `Not Started`, 
       `Total`, 
       CASE WHEN `Complete` = `Total` THEN 'Y' ELSE 'N' END `Ready`
  FROM (
SELECT pc.Sub,
    SUM(CASE WHEN `SheetStatus` LIKE 'Complete' THEN 1 ELSE 0 END) AS `Complete`,
    SUM(CASE WHEN `SheetStatus` LIKE 'Not started' THEN 1 ELSE 0 END) AS `Not Started`,
    SUM(CASE WHEN `CheckSheet` LIKE '%' THEN 1 ELSE 0 END) AS `Total`        
FROM `pc`
GROUP BY pc.Sub WITH ROLLUP) t

答案 1 :(得分:0)

试试这个:

SELECT pc.Sub,
    SUM(IF(`SheetStatus`='Complete',1,0) AS 'Complete',
    SUM(IF(`SheetStatus`='Not started',1,0) AS 'Not Started',
    SUM(IF(`CheckSheet` LIKE '%',1,0) AS 'Total'
    IF(SUM(IF(`CheckSheet` LIKE '%',1,0) = SUM(IF(`SheetStatus`='Complete',1,0),"Y","N") AS Ready
FROM `pc`
Group By pc.Sub WITH ROLLUP