Reputation: 51
I am trying to get my SQL output in the format below.
I am able to get the following output from POSTGRESQL
How can I pivot this and add a 'Year' column that classifies the row as 'Last Year' or 'Current Year' and assigns the value appropriately?
The code I have is:
Select Sales_Group, Sum(Last_Jul), Sum(Last_Aug), Sum(Current_Jul), Sum(Current_Aug)
FROM MKT_SALES_DATA
where Sales_Group = 'G1'
GROUP by Sales_Group
Any advice on how this can be achieved?
Thanks!
Upvotes: 0
Views: 40
Reputation: 12299
WITH T
(
"GROUP"
, LAST_JUL
, LAST_AUG
, CURRENT_JUL
, CURRENT_AUG
)
AS
(
VALUES
('G1', 500, 300, 800, 500)
)
SELECT T."GROUP", V.YEAR, V.JUL, V.AUGUST
FROM T
CROSS JOIN LATERAL
(
VALUES
('Last Year', T.LAST_JUL, T.LAST_AUG)
, ('Current Year', T.CURRENT_JUL, T.CURRENT_AUG)
) V (YEAR, JUL, AUGUST)
GROUP | year | jul | august |
---|---|---|---|
G1 | Last Year | 500 | 300 |
G1 | Current Year | 800 | 500 |
Upvotes: 1