我有一个名为'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
任何人都知道怎么做到这一点?
感谢帮助,谢谢。
答案 0 :(得分:3)
您可以使用条件求和来获得所需的结果。
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的事实,但我个人认为上述最佳方式表达了开发人员的意图。
答案 1 :(得分:1)
使用CASE
中的SELECT
语句,使用状态值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来尝试语法并验证它。对于那个很抱歉。但这应该让你前进。