[英]MySQL multiple count in single query
我有一個名為'sales'的表,其中包含以下字段
salesid (type: int)
stime (type: datetime)
status (type: enum, values: remaining OR cancelled OR done)
... and other fields
我需要一個可以輸出的查詢
SalesDate TotalSales TotalDone TotalRemaining TotalCancelled
2010-11-06 10 5 3 2
2010-11-06 15 14 1 0
誰知道如何實現這一目標?
幫助表示感謝,謝謝。
您可以使用條件求和來獲得所需的結果。
select stime as sales_date
,sum(1) as total_sales
,sum(case when status = 'remaining' then 1 else 0 end) as total_done
,sum(case when status = 'cancelled' then 1 else 0 end) as total_remaining
,sum(case when status = 'done' then 1 else 0 end) as total_cancelled
from sales
group by stime;
您也可以使用COUNT( expr )並利用它不包含NULLS的事實,但我個人認為上述最佳方式表達了開發人員的意圖。
在SELECT
使用CASE
語句,使用remaining, cancelled
和已done
的狀態值創建偽列
SELECT
date(stime),
COUNT(salesid),
SUM(CASE status WHEN 'done' THEN 1 ELSE 0 END) as TotalDone,
SUM(CASE status WHEN 'remaining' THEN 1 ELSE 0 END) as TotalRemaining,
SUM(CASE status WHEN 'cancelled' THEN 1 ELSE 0 END) as TotalCancelled
FROM sales
GROUP BY date(stime)
注意:這是我試圖引用的內容。 我認為這應該工作,但我無法訪問MySQL來嘗試語法並驗證它。 對於那個很抱歉。 但這應該讓你去。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.