i have multiple rows and want to make dynamic column i tried below code with case it work fine but i need the column to be dynamic based on the count of max Code
| EventId | Code | Date |
|---|---|---|
| 1 | A12 | 12/12/2020 |
| 1 | A13 | 12/12/2020 |
| 2 | A12 | 12/12/2020 |
| 2 | A13 | 12/12/2020 |
| 3 | A13 | 12/12/2020 |
i want it like below table
| EventId | Code1 | Date1 | Code2 | Date2 |
|---|---|---|---|---|
| 1 | A12 | 12/12/2020 | A13 | 12/12/2020 |
| 2 | A12 | 12/12/2020 | A13 | 12/11/2020 |
| 3 | A13 | 12/12/2021 |
WITH Ranked AS (
SELECT
EventID,
Date,
Code
rn = ROW_NUMBER() OVER (PARTITION BY EventID ORDER BY Date)
FROM TableEvent
)
SELECT
EventID,
MAX(CASE WHEN rn = 1 THEN Date END) AS Date1,
MAX(CASE WHEN rn = 1 THEN Code END) AS Code1,
MAX(CASE WHEN rn = 2 THEN Date END) AS Date2,
MAX(CASE WHEN rn = 2 THEN Code END) AS Code2,
FROM Ranked
GROUP BY EventID;