我有一个帐户表,其中一个名为" dateCreation"是创建帐户的日期。
我想在过去12个月内获得所有创建的帐户,但有时在2个月或更长时间内没有创建帐户。对于这几个月,我觉得mysql会返回0.我的请求工作正常(我在stackoverflow上得到它):
SELECT customers.dateCreation, Months.id AS `month`, Months.mois, COUNT(customers.dateCreation) AS `count`
FROM
(
SELECT 1 as ID, 'Janvier' as mois UNION SELECT 2 as ID, 'Février' as mois UNION SELECT 3 as ID, 'Mars' as mois UNION SELECT 4 as ID, 'Avril' as mois
UNION
SELECT 5 as ID, 'Mai' as mois UNION SELECT 6 as ID, 'Juin' as mois UNION SELECT 7 as ID, 'Juillet' as mois UNION SELECT 8 as ID , 'Aout' as mois
UNION
SELECT 9 as ID, 'Septembre' as mois UNION SELECT 10 as ID, 'Octobre' as mois UNION SELECT 11 as ID, 'Novembre' as mois UNION SELECT 12 as ID, 'Decembre' as mois
) as Months
LEFT JOIN customers on Months.id=month(customers.dateCreation) AND dateCreation BETWEEN Date_add(Now(),interval - 12 month) AND NOW()
GROUP BY Months.id
ORDER BY Months.id ASC
但它会返回类似的内容:
ID | Count
1 | 0
2 | 0
3 | 0
4 | 0
5 | 8
6 | 1
7 | 0
8 | 1
9 | 0
10 | 7
11 | 0
12 | 4
但我们9月份,所以我希望第一个月是10月
这是一个sqlfiddle:http://sqlfiddle.com/#!9/edfeb/1
答案 0 :(得分:3)
将您的订单修改为:
ORDER BY
CASE WHEN Months.id > MONTH(NOW()) -- check if the month is after the current
THEN 0 -- order by months after the current first
ELSE 1 -- and then by the months up to the current
END,
Months.id ASC
请参阅fiddle
答案 1 :(得分:0)
请替换左连接尝试此操作:
LEFT JOIN customers ON Months.id=MONTH(customers.dateCreation)
AND dateCreation BETWEEN DATE_ADD(CURDATE(),INTERVAL - 12 MONTH) AND CURDATE()