简化日期之间的Sum()

时间:2016-10-30 23:01:21

标签: sql postgresql

当我运行下面的查询时,创建的temp_08.members表只有一列(Q4'10),它是所有计算的总和。这是不正确的。

INSTEAD我正在尝试为每个季度创建一个单独的列,其中只有该季度内的数据的总和(计算)。出于某种原因,下面的查询无法实现此目的。

其次,是否有更有效的方法来编写此查询。我将有20个季度,每个更改的唯一内容是列名称(作为Q4_16)和每个选择的日期。

SELECT
sum(calc) as Q4_10,
brand
into   temp_08.members
from temp_08.source
WHERE    date > '09/30/2010' and date <= '12/31/2010'
GROUP BY brand

insert into temp_08.members
SELECT
sum(calc) as Q1_11,
brand
from temp_08.source
WHERE    date > '12/31/2010' and date <= '3/31/2011'
GROUP BY brand

insert into temp_08.members
SELECT
sum(calc) as Q2_11,
brand
from temp_08.source
WHERE    date > '3/31/2011' and date <= '6/30/2011'
GROUP BY brand

insert into temp_08.members
SELECT
sum(calc) as Q3_11,
brand
from temp_08.source
WHERE    date > '6/30/2011' and date <= '9/30/2011'
GROUP BY brand

insert into temp_08.members
SELECT
sum(calc) as Q4_11,
brand
from temp_08.source
WHERE    date > '9/30/2011' and date <= '12/31/2011'
GROUP BY brand

1 个答案:

答案 0 :(得分:1)

我猜你想要这样的东西:

SELECT date_trunc('quarter', date) as yyyyqq, brand, sum(calc) as sumcals,
INTO temp_08.members
FROM temp_08.source
GROUP BY date_trunc('quarter', date), brand;

您可以为要创建的所有表执行类似的操作。请注意,时间段是显式列。