MySql多次计算同一列

时间:2010-11-23 09:51:06

标签: sql mysql

SELECT COUNT(w.invoiceId) AS '10 Days' FROM tbl_Invoice w
WHERE w.invoiceId NOT IN(
SELECT inv.invoiceId FROM tbl_InvoiceAllocation inv)
AND w.invoiceDate < DATE_SUB(curdate(), INTERVAL 10 DAY)

工作正常并返回日期超过10天的所有发票的计数。我现在想要在同一查询中返回超过20天和100天的发票的计数。理想情况下,查询将返回如下内容:

10 Days    20 Days    100 Days

350        280        90

1 个答案:

答案 0 :(得分:5)

使用指定的WHERE子句作为CASE语句将COUNT更改为SUM,其中true值为1,false值为0

这样的东西
SELECT  SUM( CASE WHEN w.invoiceDate < DATE_SUB(curdate(), INTERVAL 10 DAY) THEN 1 ELSE 0 END) AS '10 Days',
        SUM( CASE WHEN w.invoiceDate < DATE_SUB(curdate(), INTERVAL 20 DAY) THEN 1 ELSE 0 END) AS '20 Days'
FROM    tbl_Invoice w 
WHERE   w.invoiceId NOT IN( 
                            SELECT  inv.invoiceId 
                            FROM    tbl_InvoiceAllocation inv) 
AND     w.invoiceDate < DATE_SUB(curdate(), INTERVAL 20 DAY)