需要 SQL:按月对值求和 [英] SQL needed: sum over values by month

查看:39
本文介绍了需要 SQL:按月对值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含如下值的表:

i have an table with values like this:

count1   count2  count3  month
12        1       4       01/12/2011
6         5       4       23/12/2011
14        6       9       11/06/2011
8         5       4       19/06/2011

如何获得以下结果?

count1   count2  count3  month
18        6       8       12
22        11      13      06

推荐答案

SELECT SUM(count1), SUM(count2), SUM(count3), MONTH(month)
  FROM myTable
 GROUP BY MONTH(month)

由于 MONTH 是 SQL Server 关键字,因此您可能需要转义列名 month(例如 [month]),如果您日期列真的是这样称呼的.(感谢 Endy 的评论!)

Since MONTH is an SQL Server keyword, you might have to escape the column name month (e.g. [month]), if you date column is really called like that. (Thanks Endy for that comment!)

此外,如果选择的数据跨度超过一年,您可能还需要按年份分组:

Also, if data selected span more than one year, you will probably need to group by year as well:

SELECT SUM(count1), SUM(count2), SUM(count3), MONTH(month), YEAR(month)
  FROM myTable
 GROUP BY MONTH(month), YEAR(month)

这篇关于需要 SQL:按月对值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆