2013-09-25 120 views
0

我有一個問題:我有兩個表在SQL Server中的逗號分隔colums

Table1其中有兩列

Col1 Col2 
---- ------ 
a  value1 
b  value1 
b  value1 

而且Table2

Col1 Col2 
---- ------ 
1  a,b 
2  a,c 
3  a,b,c 

我想導致

Col1 Col2 
----- ----- 
a  1,2,3 
b  1,3 
c  2,3 

請幫助

感謝

+0

嗯這是不可能的,因爲你不知道有字段連接表。你必須有某種鑰匙加入他們 – bksi

+1

表1與這個問題有什麼關係?它看起來像你想要的結果中的所有數據都包含在表2中 –

回答

0

試試這個:

注:沒有測試

select col1, [col2], 
(select col1+',' from Table2 where Col2=ID 
group by col1 for xml path('')) AS Col2 
From Table1 
1
WITH C AS 
(
    SELECT T2.Col1, 
     S.Item 
    FROM Table2 AS T2 
    CROSS APPLY dbo.SplitStrings(T2.Col2, ',') AS S 
) 
SELECT C1.Item AS Col1, 
     (
     SELECT ','+CAST(C2.Col1 AS VARCHAR(10)) 
     FROM C AS C2 
     WHERE C1.Item = C2.Item 
     ORDER BY C2.Col1 
     FOR XML PATH(''), TYPE 
     ).value('substring(text()[1], 2)', 'VARCHAR(MAX)') AS Col2 
FROM C AS C1 
GROUP BY C1.Item 

SQL Fiddle

+0

感謝您的幫助 –