SQL Server 需要SQL:按月对值求和

wvmv3b1j  于 2023-02-03  发布在  其他
关注(0)|答案(4)|浏览(207)

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

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
stszievb

stszievb1#

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

由于MONTH是SQL Server关键字,如果您的date列真的是这样命名的,那么您可能必须对列名month进行转义(例如[month])。(感谢Endy的评论!)
此外,如果所选数据跨越一年以上,则可能还需要按年分组:

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

rkue9o1l2#

减轻查询负担

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

pexxcrt23#

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

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

rxztt3cl

rxztt3cl4#

SELECT
SUM(count1) as sum_count1,
to_char(month, 'yyyy-MM') as month
FROM
dataframe 
GROUP BY
month

相关问题