我有值的表:逗號分隔的結果,對多個列的SQL Server
Key1 Key2 ColumnKey
============================
1 idx1 here
2 idx2 there
我需要返回,由逗號分隔的多個列的結果。
例子:
1,2 idx1,idx2, here,there
我有值的表:逗號分隔的結果,對多個列的SQL Server
Key1 Key2 ColumnKey
============================
1 idx1 here
2 idx2 there
我需要返回,由逗號分隔的多個列的結果。
例子:
1,2 idx1,idx2, here,there
select stuff(T.X.query('Key1').value('.', 'varchar(max)'), 1, 1, '') as Key1,
stuff(T.X.query('Key2').value('.', 'varchar(max)'), 1, 1, '') as Key2,
stuff(T.X.query('ColumnKey').value('.', 'varchar(max)'), 1, 1, '') as ColumnKey
from
(
select ','+cast(Key1 as varchar(10)) as Key1,
','+Key2 as Key2,
','+ColumnKey as ColumnKey
from YourTable
order by Key1
for xml path(''), type
) T(X)
謝謝Mikeal!你使我的查詢變得簡單。 –
有人可以分享這裏使用的技術名稱嗎?具體來說,T(X)=> T.X.query('Key1') – Sal
試試這個:
;WITH CTE as(
select *,1 rn from test101)
select (STUFF((select ','+cast(Key1 as varchar(10)) from CTE where CTE.rn=m.rn for xml path('')),1,1,'')) key1,
(STUFF((select ','+Key2 from CTE where CTE.rn=m.rn for xml path('')),1,1,'')) key2,
(STUFF((select ','+ColumnKey from CTE where CTE.rn=m.rn for xml path('')),1,1,'')) ColumnKey
from CTE m
group by rn
你意識到了CodePlex上有定義的聚集GROUP_CONCAT的用戶一個開放源碼的CLR實現安裝與運行SQL一樣簡單腳本在您的服務器上。
http://groupconcat.codeplex.com/
它有4 GROUP_CONCAT實施
GROUP_CONCAT --default分隔符爲,(逗號)
GROUP_CONCAT_D - 你可以指定分隔符
GROUP_CONCAT_DS - 您可以指定分隔符,排序順序(1 as asc order,2 as desc order)
個GROUP_CONCAT_S - 你可以指定排序順序
那麼你嘗試過什麼? –
相同http://stackoverflow.com/questions/941103/concat-groups-in-sql-server我認爲 – Barmar
我有解決方案,但只爲一列。 –