I have data which looks like this:
| Name | Date | Bal |
|---|---|---|
| John | 2022-01-01 | 10 |
| John | 2022-01-02 | 4 |
| John | 2022-01-03 | 7 |
| David | 2022-01-01 | 13 |
| David | 2022-01-02 | 15 |
| David | 2022-01-03 | 20 |
I want the Bal column populated under date column, like:
| Name | 2022-01-01 | 2022-01-02 | 2022-01-03 |
|---|---|---|---|
| John | 10 | 4 | 7 |
| David | 13 | 15 | 20 |
What I tried is
SELECT
NAME,
CASE WHEN DATE= '2022-01-01' THEN EOD_BALANCE ELSE NULL END "01-Jan-22",
CASE WHEN DATE= '2022-01-02' THEN EOD_BALANCE ELSE NULL END "02-Jan-22"
FROM TABL1
but I am not getting the required results. Below are the results from query in first answer:
CodePudding user response:
You want a pivot query here, which means you should aggregate by name and then take the max of the CASE expressions:
SELECT
NAME,
MAX(CASE WHEN DATE = '2022-01-01' THEN EOD_BALANCE END) AS "01-Jan-22",
MAX(CASE WHEN DATE = '2022-01-02' THEN EOD_BALANCE END) AS "02-Jan-22",
MAX(CASE WHEN DATE = '2022-01-03' THEN EOD_BALANCE END) AS "03-Jan-22"
FROM TABL1
GROUP BY NAME;

