我有这个SELECT语句:
SELECT TASK_ID, INVOICED, DELETE_WEEK,
SUM(MON_BILL+TUE_BILL+WED_BILL+THU_BILL+FRI_BILL) AS hours
FROM b_report_week
WHERE INVOICE = 1 AND DELETE_WEEK = 0
GROUP BY TASK_ID
我需要在此查询中添加另一个带有SUM的SELECT语句以提供结果:
WHERE INVOICE = 0
而不是前一个声明中的1。它仍然需要按TASK_ID分组,DELETE_WEEK仍需要为0.我试过这个:
SELECT TASK_ID, INVOICED, DELETE_WEEK,
SUM(MON_BILL+TUE_BILL+WED_BILL+THU_BILL+FRI_BILL) AS hours,
(SELECT SUM(MON_BILL+TUE_BILL+WED_BILL+THU_BILL+FRI_BILL) AS hours2
FROM b_report_week WHERE INVOICE = 0 AND DELETE_WEEK = 0 GROUP BY TASK_ID)
FROM b_report_week
WHERE INVOICE = 1 AND DELETE_WEEK = 0
GROUP BY TASK_ID
但这显然不正确。我需要使用小时和小时2在PHP while循环中输出正确的结果。帮助将不胜感激
答案 0 :(得分:0)
您可以使用Case语句:
SELECT TASK_ID, INVOICED, DELETE_WEEK,
case when INVOICE = 1 then SUM(MON_BILL+TUE_BILL+WED_BILL+THU_BILL+FRI_BILL) else 0 end AS hours,
case when INVOICE = 0 then SUM(MON_BILL+TUE_BILL+WED_BILL+THU_BILL+FRI_BILL) else 0 end AS hours2,
FROM b_report_week
WHERE DELETE_WEEK = 0
GROUP BY TASK_ID
(注意 - 必须更改where子句以避免将结果限制为Invoice = 1.)
答案 1 :(得分:0)
使用CASE
SELECT TASK_ID, INVOICED, DELETE_WEEK,
SUM(MON_BILL+TUE_BILL+WED_BILL+THU_BILL+FRI_BILL) AS hours ,
SUM(CASE WHEN INVOICE = 0 then MON_BILL+TUE_BILL+WED_BILL+THU_BILL+FRI_BILL else o end case) as custom_sum
FROM b_report_week
WHERE DELETE_WEEK = 0
GROUP BY TASK_ID
答案 2 :(得分:0)
您也可以使用UNION子句
解决它SELECT TASK_ID, INVOICED, DELETE_WEEK,
SUM(MON_BILL+TUE_BILL+WED_BILL+THU_BILL+FRI_BILL) AS hours
FROM b_report_week
WHERE INVOICE = 1 AND DELETE_WEEK = 0
GROUP BY TASK_ID
UNION
SELECT TASK_ID, INVOICED, DELETE_WEEK,
SUM(MON_BILL+TUE_BILL+WED_BILL+THU_BILL+FRI_BILL) AS hours
FROM b_report_week
WHERE INVOICE = 0 AND DELETE_WEEK = 0
GROUP BY TASK_ID
但我认为更容易阅读CASE WHEN条款