2012-12-26 89 views
0

我正在使用PostgreSQL。
我有一個表像下面:Postgres查詢以獲取數據datewise

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年中數量字段的也就是產品的明智之和):

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

回答

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; 

要resuse的計算本年初我CROSS JOIN它作爲子查詢x