我有一个包含这些列的订单表:order_item order_category order_date 所以数据看起来像这样:
order_item order_category order_date
1235 hardware 2014-01-07
1349 bedding 2014-01-07
1636 hardware 2014-01-08
等
大约有20个产品类别。此查询可以获取每天按类别排序的项目数:
SELECT order_date, count(order_item) as num, order_category
FROM orders
GROUP BY order_date, order_category
我想得到一个显示月份和每个类别的计数的结果,所以它看起来像这样:
month bedding hardware etc
2013-12 5 8
2014-01 9 0
我可以用mysql做这个吗?
答案 0 :(得分:0)
您还必须按年分组,否则您将获得每年“每个1月”的结果。
SELECT order_date, count(order_item) as num, order_category
FROM orders
GROUP BY order_category, year(datefield), month(date field) desc;
一个简单的google for'mysql group by year and month'给出了这个好帖子......
答案 1 :(得分:0)
试试这个:
SELECT '2014-01' month , SUM(CASE WHEN order_category = 'hardware'
THEN 1 ELSE 0 END )as hardware,
SUM(CASE WHEN order_category = 'bedding'
THEN 1 ELSE 0 END )as bedding
FROM Table1
WHERE MONTH(order_date) = 01 AND year(order_date) = 2014
UNION all
SELECT '2013-12' month , SUM(CASE WHEN order_category = 'hardware'
THEN 1 ELSE 0 END )as hardware,
SUM(CASE WHEN order_category = 'bedding'
THEN 1 ELSE 0 END )as bedding
FROM Table1
WHERE MONTH(order_date) = 12 AND year(order_date) = 2013