在Vertica中按月汇总数据

时间:2016-08-22 12:36:02

标签: sql vertica

我有一个这样的Vertica表:

date number
'2016-01-01' 47
'2016-01-02' 32
'2016-04-13' 54

我想这样总结一下:

Jan Feb Mar Apr ...
150 102 30 0

第二行是该月所有数字的总和。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您需要使用case语句在每个列上创建一个总和,以仅对正确的值求和。

SELECT SUM(CASE WHEN MONTH("DATE") = 1 THEN "NUMBER" END) Jan,
       SUM(CASE WHEN MONTH("DATE") = 2 THEN "NUMBER" END) Feb,
       SUM(CASE WHEN MONTH("DATE") = 3 THEN "NUMBER" END) Mar,
       SUM(CASE WHEN MONTH("DATE") = 4 THEN "NUMBER" END) Apr,
       SUM(CASE WHEN MONTH("DATE") = 5 THEN "NUMBER" END) May,
       SUM(CASE WHEN MONTH("DATE") = 6 THEN "NUMBER" END) Jun,
       SUM(CASE WHEN MONTH("DATE") = 7 THEN "NUMBER" END) Jul,
       SUM(CASE WHEN MONTH("DATE") = 8 THEN "NUMBER" END) Aug,
       SUM(CASE WHEN MONTH("DATE") = 9 THEN "NUMBER" END) Sep,
       SUM(CASE WHEN MONTH("DATE") = 10 THEN "NUMBER" END) Oct,
       SUM(CASE WHEN MONTH("DATE") = 11 THEN "NUMBER" END) Nov,
       SUM(CASE WHEN MONTH("DATE") = 12 THEN "NUMBER" END) Dec
FROM mytable

您还可以添加另一个字段来执行此操作,然后对其进行分组/排序(如果这是您要执行的操作)。 YEAR("DATE")