2009-06-25 69 views
0

我有一個MS SQL查詢聯接多個表和結果的一個例子是:SQL查詢鮮明列串連另一列

EmailAddress   Column2          
--------------------- ---------------- 
[email protected]   Value1          
[email protected]   Value2 
[email protected]   Value5 


What I really want to achieve are the following results: 


EmailAddress   Column2          
--------------------- ------------------ 
[email protected]   Value1, Value2 
[email protected]   Value5 

但是也有一些具有相同的電子郵件地址的每一行相同的其他列。任何人都可以幫助我使用SQL返回不同的電子郵件地址並連接column2信息嗎?

感謝您的任何反饋意見。

回答

1

嘗試回答this question

+0

這並獲得成功,謝謝傑里米 – Sean 2009-06-25 13:08:38

0

SQL Server 2005+

WITH q AS 
     (
     SELECT '[email protected]' AS address, 'Value1' AS value 
     UNION ALL 
     SELECT '[email protected]', 'Value2' 
     UNION ALL 
     SELECT '[email protected]', 'Value5' 
     ) 
SELECT (
     SELECT CASE WHEN ROW_NUMBER() OVER (ORDER BY value) > 1 THEN ', ' ELSE '' END + value 
     FROM q qi 
     WHERE qi.address = qo.address 
     FOR XML PATH('') 
     ) 
FROM (
     SELECT DISTINCT address 
     FROM q 
     ) qo 
0

傑里米相同的答案,但我會用other答案與XML PATH