我有一个表MySeekCatTable
,其结构为:
SeekId CatId
J 1<= i<=45
在此表中,每个SeekId
都有三个CatId
。
表MySeekCatTable
引用带有外键的两个表:
以SeekTable
为主键的第一个表SeekId
如下:
SeekId Name
1 John
2 Kelly
以CatTable
为主键的第二个表CatId
如下:
CatId Name
1 Cat1
2 Cat2
我需要的是,我必须编写一个查询,其格式为其SeekId
中的每个CatId
三个:
SeekId A B C
1 Cat1 Cat2 Cat3
i Cati Catj Catk
答案 0 :(得分:1)
;WITH cte
AS (SELECT SeekId,
CatId,
ct.Name,
ROW_NUMBER() OVER (PARTITION BY SeekId ORDER BY CatId) AS RN
FROM MySeekCatTable sk
JOIN CatTable ct
ON sk.CatId = ct.CatId)
SELECT SeekId,
MAX(CASE WHEN RN = 1 THEN Name END) AS A,
MAX(CASE WHEN RN = 2 THEN Name END) AS B,
MAX(CASE WHEN RN = 3 THEN Name END) AS C
FROM cte
GROUP BY SeekId