0

I am using PostgreSQL.
I have a table like below:

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

Now I want the result like below (i.e product wise sum of qty field of last 4 years):

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

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

To resuse the calculated beginning of the current year I CROSS JOIN it as subquery x.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.