0

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

对于每个值,我如何首先获得每月汇总结果,然后每年获得汇总结果?

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

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

4

1 回答 1

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按月生成小计和按年生成总计。外部查询格式化年份并删除总计。

于 2013-04-10T23:03:08.850 回答