每月在SQL中添加

时间:2016-01-12 13:33:44

标签: sql postgresql date sum

我需要something

的SUM列month
   date     something
 2010-01-02  
 2010-01-03  
 2010-01-04  
 2010-01-07  
 2010-01-10  
 2010-01-12  
 2010-01-13  
 2010-01-14  
 2010-01-15  
 2010-01-16  
 2010-01-17  
 2010-01-18  3
 2010-01-19  1
 2010-01-21  
 2010-01-22  11
 2010-01-23  1
 2010-01-24  
 2010-01-25  
 2010-01-26  
 2010-01-27  
 2010-01-28  
 2010-01-29  
 2010-01-30  
 2010-01-05  5
 2010-01-06  8
 2010-01-09  
 2010-01-08  3
 2010-01-11  
 2010-01-01  
 2010-01-20  0
 2010-01-31  13

输出应该是例如对于2010年1月的总和45:

   date     something
 2010-01     45

如何为此编写SQL查询?

1 个答案:

答案 0 :(得分:1)

这是一个基于date列的月份的简单聚合:

select to_char("date", 'yyyy-mm'), sum(something)
from the_table
group by to_char("date", 'yyyy-mm')

这假设列date的数据类型为date(或timestamp