2012-06-05 127 views
0

請幫助使用SQL Query來解決以下問題。我需要幫助在SQL查詢中輸入以下輸出

我有這樣一個表的輸入值 - 列標題是X和Y

x | y 
------------------- 
    1 | a1 
    1 | a2 
    2 | a3 
    2 | a4 
    2 | a2 

我需要這樣的

x | y 
---------- 
1 |a1,a2 
2 |a3,a4,a2 

請指點輸出!

+1

檢查[此](http://social.msdn.microsoft.com/Forums/en/transactsql/thread/f09d4166-2030-41fe-b86e-392fbc94db53)爲好。 – Darshana

回答

1
SELECT nto.x, STUFF((SELECT CAST(',' AS varchar(max)) + nti.y 
     FROM mytable AS nti WHERE nti.x = nto.x 
     FOR XML PATH('')), 1, 1, '') AS Y 
FROM mytable AS nto 
GROUP BY nto.x