2015-05-09 68 views
0

我從數據庫檢索今天的數據,我想檢索本月,今年的數據以及是否有可能在單個查詢?或者我應該爲每個項目單獨查詢? 下面我給出的查詢,獲取今天,本週,本月和今年的數據在MySQL中的單個查詢?

select sum(it.rate * it.quantity)as sales from invoices i 
join invoice_items it on i.id = it.invoice_id 
where i.invoice_date > DATE_SUB(NOW(), INTERVAL 1 DAY) 

回答

1

使用條件彙總:

select sum(case when i.invoice_date > DATE_SUB(NOW(), INTERVAL 1 DAY) then it.rate * it.quantity 
      end) as sales_1day, 
     sum(case when i.invoice_date > DATE_SUB(NOW(), INTERVAL 7 DAY) then it.rate * it.quantity 
      end) as sales_7day, 
     sum(case when i.invoice_date > DATE_SUB(NOW(), INTERVAL 1 MONTH) then it.rate * it.quantity 
      end) as sales_1month, 
     sum(case when i.invoice_date > DATE_SUB(NOW(), INTERVAL 1 YEAR) then it.rate * it.quantity 
      end) as sales_1year  
from invoices i join 
    invoice_items it 
    on i.id = it.invoice_id 
+0

謝謝..它看起來很大.. :) – gsk

相關問題