0

我正在使用 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 年 qty 字段的产品明智总和):

product_id
QTY(current_year)  
QTY( current year + last_year)  
QTY_last2_years 
QTY > 2 years
4

1 回答 1

1
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;

要重新使用计算出的当年年初,我CROSS JOIN将其作为子查询x

于 2012-12-26T06:58:45.820 回答