需要SQL:按月汇总值

时间:2011-04-21 07:59:08

标签: sql-server sql-server-2005

我有一个像这样的值的表:

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

4 个答案:

答案 0 :(得分:19)

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

由于MONTH是SQL Server关键字,因此您可能必须转义列名称month(例如[month]),如果您真的调用了日期列。 (感谢恩迪的评论!)

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

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

答案 1 :(得分:2)

减轻查询负担

SELECT SUM(count1), SUM(count2), SUM(count3), substring(month,4,2)   
FROM myTable  
GROUP BY substring(month,4,2)

答案 2 :(得分:0)

SELECT SUM(count1), SUM(count2), SUM(count3), MONTH(month)   
FROM Table  
GROUP BY trunc(month,'mm')

这将在PL / SQL开发人员中运行:)

答案 3 :(得分:0)

# this might help
cmd=int(input('Enter integer\n'))
temporary1=list()
temporary2=0
for i in range(int(len(data[position]['content'][1])/cmd)):
    temporary1.append([])
for a in range(len(temporary1)):
    for b in range(cmd):
        temporary1[a].append(data[position]['content'][1][temporary2])
        temporary2+=1

# The problem is under this comment
for a in range(len(temporary1)):
    for b in range(len(temporary1[a])):
        temporary1[a][b].append(2)
print(temporary1)