在自定义日期间

时间:2016-10-31 01:48:44

标签: 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/29/2010'
GROUP BY brand

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

insert into temp_08.members
SELECT
sum(calc) as Q2_11,
brand
from temp_08.source
WHERE    date > '3/28/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/25/2011'
GROUP BY brand

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

2 个答案:

答案 0 :(得分:1)

你应该有一个定义季度的表格。在查询中,您可以使用CTE执行此操作:

with q(qqyy, firstday, lastday) as (
      (values ('Q4_10','2010-10-01', '2010-12-29'),
              . . .
      ))
SELECT q.qqyy, brand, sum(calc) as Q4_10,
into   temp_08.members
from temp_08.source s join
     q
     on s.date >= q.firstday and s.date <= q.lastday
GROUP BY q.qqyy, brand;

编辑:

CTE的一个例子:

with q(qqyy, firstday, lastday) as (
      (values ('Q4_10', date '2010-10-01', date '2010-12-29'),
              ('Q1_11', date '2010-12-30', date '2011-03-28'),
              ('Q2_11', date '2011-03-29', date '2011-06-30')
      ))
select * from q

答案 1 :(得分:1)

您可以定义一个表格,其中包含每个季度所涵盖的季度和日期(这会简化插入的次数):

create table temp_08.quarters (
    quarter_col text
  , date_from   date
  , date_to     date
);

insert into temp_08.quarters 
  values 
    ('Q4_10', '2010-09-30', '2010-12-29'),
    ('Q1_11', '2010-12-29', '2011-03-28'),
    ...
;

创建您的成员表:

create table temp_08.members (
    brand       text
  , quarter_col text
  , calc_sum    bigint -- or whatever type you like
);

然后,您只需将其插入到您的成员表中:

INSERT INTO temp_08.members ( brand, quarter_col, calc_sum )
  SELECT 
      s.brand
    , q.quarter_col
    , sum(s.calc) as calc_sum
  FROM temp_08.source s
  JOIN temp_08.quarters q ON s.date > q.date_from AND s.date <= q.date_to 
  GROUP BY s.brand, q.quarter_col;