MySql counts the 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 great and returns an invoice for all invoices with a date more than 10 days ago. Now I want to return invoices for invoices that also contain more than 20 and 100 days in one request. Therefore, ideally, the query returns something like this:

10 Days    20 Days    100 Days

350        280        90
+3
source share
1 answer

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

Sort of

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)
+5
source

Source: https://habr.com/ru/post/1776414/


All Articles