2010-11-23 71 views
3
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天的發票的計數。因此,理想情況下,查詢將返回這樣的事:MySql Count同一列多次

10 Days 20 Days 100 Days 

350  280  90 
+0

看到這一點,需要留下同桌http://stackoverflow.com/questions/2300020/mysql-multiple-counts-in-single-query加入 – 2010-11-23 09:56:26

回答

5

修改計數的款項,使用指定的WHERE子句中的CASE語句,與真實值1和假值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) 
+0

感謝這個工作,但沒有 和W .invoiceDate Pjn2020 2010-11-23 10:11:26