为此使用递归查询:
--Prepare Dummy Data
;WITH CITIES
AS (SELECT 100 AS City_Code,
'A1' AS Post_code,
'ABC' AS Post_Code_Description
UNION
SELECT 100 AS City_Code,
'C8' AS Post_code,
'XYZ' AS Post_Code_Description
UNION
SELECT 100 AS City_Code,
'Z3' AS Post_code,
'MNO' AS Post_Code_Description
UNION
SELECT 200 AS City_Code,
'D4' AS Post_code,
'LMN' AS Post_Code_Description
UNION
SELECT 300 AS City_Code,
'E3' AS Post_code,
'IJK' AS Post_Code_Description
UNION
SELECT 300 AS City_Code,
'B9' AS Post_code,
'RST' AS Post_Code_Description),
--Add Row numbers to each row
PREPARE
AS (SELECT *,
ROW_NUMBER ()
OVER (
PARTITION BY CITY_CODE
ORDER BY CITY_CODE) RN
FROM CITIES),
--Start Recursive CTE
RECURSIVE
AS (
--Anchor Query
SELECT CITY_CODE,
CAST(POST_CODE AS VARCHAR(MAX)) Post_code,
CAST(POST_CODE_DESCRIPTION AS VARCHAR(MAX))
Post_Code_Description,
1 AS LEVEL,
RN
FROM PREPARE
WHERE RN = 1
UNION ALL
--Recursive Query
SELECT T1.CITY_CODE,
T1.POST_CODE + ',' + T2.POST_CODE,
T1.POST_CODE_DESCRIPTION + ','
+ T2.POST_CODE_DESCRIPTION,
T2.LEVEL + 1,
T1.RN
FROM PREPARE AS T1
INNER JOIN RECURSIVE AS T2
ON T1.RN = T2.RN + 1
AND T1.CITY_CODE = T2.CITY_CODE)
--Final Results
SELECT T1.CITY_CODE,
T1.POST_CODE,
T1.POST_CODE_DESCRIPTION
FROM RECURSIVE T1
INNER JOIN (SELECT CITY_CODE,
COUNT(*) cnt
FROM CITIES
GROUP BY CITY_CODE)T2
ON T1.CITY_CODE = T2.CITY_CODE
WHERE T1.LEVEL = T2.CNT