MySql Group by Month

时间:2014-02-24 11:28:48

标签: mysql group-by

我有一组日期和相应的销售额,我希望每个月按月分组 不可能几个月的进入不存在,如果是这样,那么相应的月份值将是0,否则其他月份可用的数额。

3 个答案:

答案 0 :(得分:0)

你可以尝试: //这将为您提供所需月份的所有条目

SELECT * FROM tbl1 WHERE date=MONTH('datecolumn_name') ORDER BY MONTH(datecolumn_name) ASC;

答案 1 :(得分:0)

juz run thiz query你明白了:

(SELECT @d:= date_add(@ d,interval 1 MONTH)AS month_view,date_format(@ c,'%b-%Y')AS month_name,@ a:= @c AS month_start,@ b:= if(last_day(@a)>'2014-02-24','2014-02-24',last_day(@a))AS month_end,@ c:= CASE WHEN date_add(@ b,interval 1 DAY)&gt ;'2014-02-24'THEN NULL ELSE date_add(@ b,INTERVAL 1 DAY)END AS dummy_val FROM table_name, (SELECT @c:='2013-01-01',@ d:='2013-01-01')AS month_temp WHERE @c IS NOT NULL)

'table_name'给出来自ur database的任何表名

FROM_DATE = 2013-01-01 TO_DATE = 2014年2月24日

答案 2 :(得分:0)

这样的事情可能会成功: - 但是你需要照顾好几年,这只是基于月份的

SELECT s1.m as mnth,IFNULL(s2.smv,0) as smv FROM
(SELECT 1 as m UNION 
SELECT 2 UNION 
SELECT 3 UNION 
SELECT 4 UNION 
SELECT 5 UNION 
SELECT 6 UNION 
SELECT 7 UNION 
SELECT 8 UNION 
SELECT 9 UNION 
SELECT 10 UNION 
SELECT 11 UNION 
SELECT 12) s1
LEFT JOIN
(SELECT MONTH(startdatum) as mnth, 
SUM(somevalue) as smv
FROM db_table GROUP BY mnth) s2
ON s1.m=s2.mnth