MySql查询每年或每月汇总

时间:2013-04-10 22:47:50

标签: mysql checksum

我有以下表格结构: 使用DailyDate ex的table = {id,DailyDate,value1,value2}。 2000-01-01

我如何能够每月获得一次总结结果,其次是每年每次获得一次总结结果?

我正在尝试以下但不起作用

Select Sum(Value1),Year(DailyDate),Month(DailyDate)
From table
Group by Year(DailyDate),Month(DailyDate)
Order by Year(DailyDate),Month(DailyDate)

TY

1 个答案:

答案 0 :(得分:2)

如果您要求的是按年份小计,请尝试以下方法:

SELECT TheSum, TheYear, COALESCE(TheMonth, CONCAT('Total Year ', TheYear))
FROM (
  SELECT
    SUM(Value1) TheSum,
    YEAR(DailyDate) AS TheYear,
    MONTH(DailyDate) AS TheMonth
  FROM table
  GROUP BY Year(DailyDate), MONTH(DailyDate) WITH ROLLUP) x
WHERE TheYear IS NOT NULL

内部查询使用WITH ROLLUP按月生成小计,按年生成总计。外部查询格式化年份并删除总计。