以下是我的问题的示例表:
100 IDO 0514443421
100 IDO 0504899721
100 IDO 0508843421
101 LIRAN 0523399721
101 LIRAN 0524899721
102 ERAN 0593369721
102 ERAN 0599999721
我想回到这样一行:
100, IDO, 0514443421, 0504899721, 0508843421
我知道行号变化的问题。我可以解决固定的3个输出列,其中一些可能是空的。
实现这一目标的任何好方法?
提前感谢你。
答案 0 :(得分:4)
假设最近的SQL Server并基于优秀建议here,这将分别选择前两列,最后一部分作为逗号分隔字符串;
SELECT id, ColA,
REPLACE(
(SELECT ColB AS [data()]
FROM TableA a2
WHERE a1.id=a2.id
ORDER BY a2.ColB FOR XML PATH('')),
' ', ', ')
FROM TableA a1
GROUP BY id, ColA;
演示here。
编辑:当然,如果你愿意,你可以将它全部作为单个字符串,只需用
替换第一行SELECT CAST(id AS VARCHAR(16)) + ', ' + ColA + ', ' +
答案 1 :(得分:0)
尝试:
;with cte as
(select id,
colA,
colB,
rownumber() over (partition by id, colA order by colB) rn
from myTable)
select id, colA, t1.colB colB1, t2.colB colB2, t3.colB colB3
from cte t1
left join cte t2 on t1.id = t2.id and t1.colA = t2.colA and t2.rn = 2
left join cte t3 on t1.id = t3.id and t1.colA = t3.colA and t3.rn = 3
where t1.rn = 1