我有以下列的表财务: | ID |年|本月|值| 我的选择是:
SELECT VALUE, YEAR, MONTH
FROM FINANCE GROUP BY YEAR
结果是:
3056.25, 2015, I
3445.62, 2015, II
3445.62, 2015, III
9251.22, 2015, IV
3445.62, 2015, V
8102.00, 2015, VI
8753.25, 2015, VII
3204.00, 2015, XIII
6555.25, 2015, IX
3206.00, 2015, X
3057.25, 2015, XI
2010.00, 2015, XII
1056.25, 2016, I
4000.00, 2016, II
我想做的是每年之后获得摘要,例如:
3056.25, 2015, I
3445.62, 2015, II
9251.22, 2015, IV
8102.00, 2015, VI
8753.25, 2015, VII
3204.00, 2015, XIII
6555.25, 2015, IX
3206.00, 2015, X
3057.25, 2015, XI
2010.00, 2015, XII
**57532,08, 2015,NULL**
1056.25, 2016, I
4000.00, 2016, II
**5056,25, 2016, NULL**
如何实现这个目标?
答案 0 :(得分:3)
您可以使用UNION ALL
添加公开值:
SELECT VALUE, YEAR, MONTH
FROM finance
UNION ALL
SELECT SUM(VALUE), YEAR, NULL
FROM finance
GROUP BY YEAR
ORDER BY YEAR, CASE WHEN MONTH = 'I' THEN 1
WHEN MONTH = 'II' THEN 2
...
ELSE 13
END;
答案 1 :(得分:1)
我想你可能想在你的用例中使用GROUP BY ROLLUP或CUBE。 多维数据集将为您提供组中每个字段的组合。
试试这个:
SELECT VALUE, YEAR, MONTH
FROM finance -- gives you the data like you have it
UNION ALL
SELECT sum(VALUE), YEAR, MONTH
FROM FINANCE GROUP BY CUBE (YEAR, MONTH) -- appends the SUM combinations of all dimensions
如果多维数据集给你"太多"尝试汇总...汇总将按照子句
维护组中的排序层次结构但实际上,如果你想将所有数据和聚合一起返回给应用程序,你也可以不去理解数据库方面的聚合,因为APP代码可以做总结...只是一个想法