如何按月对结果进行分组?

时间:2013-01-14 14:00:00

标签: mysql select group-by union

目前,我的代码产生了这样的结果:

 SELECT YEAR(date_added) AS YEAR, MONTHNAME(date_added) AS  MONTH, COUNT(*) AS TOTAL
 FROM news
 GROUP BY MONTH 

 UNION ALL 

 SELECT YEAR(date_added) AS YEAR, MONTHNAME(date_added) AS MONTH , COUNT(*) AS TOTAL
 FROM equipment
 GROUP BY MONTH 

 RESULTS:
 YEAR MONTH TOTAL
 2013 FEB    1 (news table)
 2013 JAN   12 (news table)
 2013 FEB    1 (equipment table)
 2013 JAN   11 (equipment table)

如何编辑SQL查询,以便我只能显示:

 RESULTS:
 YEAR MONTH TOTAL
 2013 FEB    2 (both news and equipment table)
 2013 JAN   23 (both news and equipment table)

提前感谢您的帮助!

4 个答案:

答案 0 :(得分:2)

尝试:

SELECT YEAR, MONTH, SUM(TOTAL) AS TOTAL
FROM (SELECT YEAR(date_added) AS YEAR, MONTHNAME(date_added) AS  MONTH, COUNT(*) AS TOTAL
 FROM news
 GROUP BY MONTH 

 UNION ALL 

 SELECT YEAR(date_added) AS YEAR, MONTHNAME(date_added) AS MONTH , COUNT(*) AS TOTAL
 FROM equipment
 GROUP BY MONTH) x
GROUP BY YEAR, MONTH

答案 1 :(得分:1)

Select year, month, sum(total) from
(
SELECT YEAR(date_added) AS YEAR, MONTHNAME(date_added) AS  MONTH, COUNT(*) AS TOTAL
 FROM news
 GROUP BY MONTH 

 UNION ALL 

 SELECT YEAR(date_added) AS YEAR, MONTHNAME(date_added) AS MONTH , COUNT(*) AS TOTAL
 FROM equipment
 GROUP BY MONTH 
)
group by year, month

答案 2 :(得分:0)

试试这个:

SELECT YEAR, MONTH, SUM(total) total 
FROM (SELECT YEAR(date_added) AS YEAR, MONTHNAME(date_added) AS MONTH, COUNT(*) AS TOTAL 
      FROM news 
      GROUP BY MONTH
      UNION ALL
      SELECT YEAR(date_added) AS YEAR, MONTHNAME(date_added) AS MONTH , COUNT(*) AS TOTAL 
      FROM equipment 
      GROUP BY MONTH
     ) AS A 
GROUP BY YEAR, MONTH

答案 3 :(得分:0)

select x.year, x.month, sum(x.total) from x(
 SELECT YEAR(date_added) AS YEAR, MONTHNAME(date_added) AS  MONTH, COUNT(*) AS TOTAL
 FROM news
 GROUP BY MONTH 

 UNION ALL 

 SELECT YEAR(date_added) AS YEAR, MONTHNAME(date_added) AS MONTH , COUNT(*) AS TOTAL
 FROM equipment
 GROUP BY MONTH ) x
group by x.month, x.year