简体   繁体   中英

MySql Count Same Column multiple times

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)

It works fine and returns a count of all the invoices that have a date of more than 10 days ago. I now want to return counts for invoices that are also more than 20 and 100 days old in the same query. So ideally the query would return something like this:

10 Days    20 Days    100 Days

350        280        90

Change the COUNT to a SUM, using the specified WHERE clause as a CASE statement, with true values as 1 and false values as 0

Something like

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM