我有两个问题:
SELECT COUNT(*) as adet, MONTHNAME(date_created) as monthname
FROM orders
WHERE YEAR(date_created) = 2017
GROUP BY MONTH(date_created)
返回此结果
adet monthname
----------------
17 January
24 February
45 March
40 April
和另一个问题:
SELECT COUNT(*) as adet, seller_id
FROM orders
WHERE YEAR(date_created) = 2017
GROUP BY seller_id
返回此结果:
adet seller_id
---------------
120 20
120 21
500 22
400 23
如何将这两个查询组合起来得到如下结果:
adet month seller_id
--------------------
-09- -Jan- --20--
-05- -Fab- --20--
-05- -Mar- --20--
...
-05- -jan- --21--
-04- -Fab- --21--
...
-05- -jan- --22--
-04- -Fab- --22--
答案 0 :(得分:3)
你可以尝试
SELECT COUNT(*) adet, LAST_DAY(date_created) month_ending, seller_id
FROM orders
WHERE date_created >= DATE_FORMAT(CURDATE(),'%Y-01-01')
AND date_created < DATE_FORMAT(CURDATE(),'%Y-01-01') + INTERVAL 1 YEAR
GROUP BY LAST_DAY(date_created), seller_id
为什么你会使用看似复杂的东西?因为
date_created
列上使用索引,因此运行得更快。答案 1 :(得分:1)
尝试以下查询:
SELECT COUNT(*) as adet, MONTHNAME(date_created) as monthname,seller_id
FROM orders where YEAR(date_created) = 2017
GROUP BY MONTH(date_created),seller_id