Getting 0 in Group By Month

时间:2015-05-04 19:46:29

标签: mysql

My Table structure is like this:

id | bileti_id | status | user_id | point | date

I want to get Number of bileti_id where status is 1 Grouped By Months, but if there is 0 in some month, give me 0 in that month and not just months where are values... So my query returns only months where user made more than 0 bileti_id.

SELECT IFNULL(COUNT(`bileti_id`),0) FROM `wp_biletistatus` WHERE `user_id`= 16590 and `status`=1 GROUP BY MONTH(`date`) ORDER BY `date` ASC Limit 10

But i have already Query which Calls these months: so i need to connect this query with previous one, to get exactly how much bileti_id user had in these months, with 0 results as well...

Here is second query:

SELECT MONTHNAME(`date`) FROM `wp_biletistatus` WHERE `user_id`= 16590 GROUP BY MONTH(`date`) ORDER BY `date` ASC Limit 10

1 个答案:

答案 0 :(得分:0)

This should be closer to what you need, but I am still not sure of the importance or significance of the LIMIT 10. Are you trying to only get data for the users last 10 months? ("ORDER BY date" doesn't seem quite right if that is the case.)

SELECT MONTHNAME(`date`) AS mName, MONTH(`date`) AS mOrder
, SUM(IF(status=1, 1, 0)) AS c
FROM `wp_biletistatus` 
WHERE `user_id`= 16590
GROUP BY mOrder
ORDER BY mOrder
;