January 13, 2020 at 5:08 am
Hi there,
I have a sql question wondering your sql expertise. My data as follows pasted in the screenshot attached and it is in the same table AS displayed below. I would like to a self join so it display as mentioned in the second sheet in the same picture attached using sql. I have tried joins, pivots and all options. Appreciate the help.
I would like to split the data side by side based on the matching Name but different flags side by side. I am ok having different column names but output should be returned from one select. hope you got my req.
Sincerely
January 13, 2020 at 4:06 pm
--to be validated
--cte or tablealias for selfjoin
WITH TABLEDATA AS
(
SELECT ...
FROM TABLE_DATA
)
SELECT TYTD.COLUMNS, TMTD.COLUMNS
FROM TABLEDATA TYTD
LEFT JOIN TABLEDATA TMTD
ON TYTD.NAME=TMTD.NAME
AND TYTD.COMPANY = TMTD.COMPANY
AND TMTD.Flag='MTD'
...
WHERE TYTD.Flag='YTD';
--also possible
SELECT YTD.columns, MTD.columns
FROM
(
SELECT ... FROM TABLE_DATA WHERE FLAG='YTD'
) SELECTION_YTD
LEFT JOIN
(
SELECT ... FROM TABLE_DATA WHERE FLAG='MTD'
) SELECTION_MTD
ON SELECTION_YTD.NAME=SELECTION_MTD.NAME
AND ...
Viewing 2 posts - 1 through 1 (of 1 total)
You must be logged in to reply to this topic. Login to reply