我有一个重复ID的表,但第二列中有其他值。 我没有使用DISTINCT删除所有重复项,而是需要带有ID的1行和带有第2列值的多个列。
这就是我的意思:(必须成为结果)
答案 0 :(得分:0)
好的,我已经成功解决了这个问题:
WITH cte AS (SELECT top 1000 *, ROW_NUMBER()OVER(PARTITION BY
id ORDER BY id) as RN FROM dbo.books) SELECT top
1000 a.id, a.category
, b.category as category2
, c.category as category3
, d.category as category4
from cte a
LEFT join cte b
on a.id = b.id
and a.RN = b.RN -1
LEFT JOIN cte c
ON a.id = c.id
AND a.RN = c.RN -2
LEFT JOIN cte d
ON a.id = d.id
AND a.RN = d.RN -3
WHERE a.RN = 1