Sql Postgres查询以按日期获取数据

Sql Postgres查询以按日期获取数据,sql,postgresql,datetime,aggregate-functions,Sql,Postgresql,Datetime,Aggregate Functions,我正在使用PostgreSQL。 我有一张如下表: ID product_id Date Qty ----------------------------------- 1 12 2008-06-02 50 2 3 2008-07-12 5 3 12 2009-02-10 25 4 10 2012-11-01 22 5 2

我正在使用PostgreSQL。
我有一张如下表:

ID   product_id   Date         Qty
-----------------------------------
1    12           2008-06-02   50
2     3           2008-07-12    5
3    12           2009-02-10   25
4    10           2012-11-01   22
5     2           2011-03-25    7
现在,我希望得到如下结果(即过去4年数量字段的产品总和):

选择产品标识
,合计(案例mydate>=x.t然后数量结束)作为当前年度的数量
,求和(案例mydate>=(x.t-间隔'1 y'),然后数量结束)作为自去年以来的数量
,总和(案例mydate>=(x.t-间隔'2 y')
和mydate
要继续使用计算出的本年度年初,请I
CROSS JOIN
it作为子查询
x

product_id
QTY(current_year)  
QTY( current year + last_year)  
QTY_last2_years 
QTY > 2 years
SELECT product_id
      ,sum(CASE mydate >=  x.t THEN qty END) AS qty_current_year
      ,sum(CASE mydate >= (x.t - interval '1 y') THEN qty END) AS qty_since_last_year
      ,sum(CASE mydate >= (x.t - interval '2 y')
            AND mydate <   x.t THEN qty END) AS qty_last_2_year
      ,sum(CASE mydate <  (x.t - interval '2 y') THEN qty END) AS qty_older
FROM   tbl
CROSS  JOIN (SELECT date_trunc('year', now()) AS t) x -- calculate once
GROUP  BY 1;