CREATE VIEW KundenRufnummern AS
WITH Rufnummern AS (
SELECT
T2.Kunden_ID,
T1.Kunden_Name,
T2.Rufnummer,
'Rufnummer' + CAST(ROW_NUMBER() OVER (PARTITION BY T2.Kunden_ID ORDER BY T2.ID) AS VARCHAR(10)) AS RufnummerLabel
FROM
Tabelle1 T1
JOIN
Tabelle2 T2 ON T1.Kunden_ID = T2.Kunden_ID
)
SELECT
Kunden_ID,
Kunden_Name,
MAX(CASE WHEN RufnummerLabel = 'Rufnummer1' THEN Rufnummer ELSE NULL END) AS Rufnummer1,
MAX(CASE WHEN RufnummerLabel = 'Rufnummer2' THEN Rufnummer ELSE NULL END) AS Rufnummer2,
MAX(CASE WHEN RufnummerLabel = 'Rufnummer3' THEN Rufnummer ELSE NULL END) AS Rufnummer3,
MAX(CASE WHEN RufnummerLabel = 'Rufnummer4' THEN Rufnummer ELSE NULL END) AS Rufnummer4,
MAX(CASE WHEN RufnummerLabel = 'Rufnummer5' THEN Rufnummer ELSE NULL END) AS Rufnummer5
FROM
Rufnummern
GROUP BY
Kunden_ID, Kunden_Name;