2013-11-20 50 views
0

伊夫加入使用分隔符的第二列值的SQL表看起來像這樣在第一列組相似的價值觀和SQL

ID  |  Pattern 
--------------------- 
1  |  2345 
2  |  3345 
3  |  2345 
4  |  5647 
5  |  1472 
6  |  4817 
7  |  5871 
8  |  2345 
9  |  5871 
10  |  1472 

這裏的模式只是一些隨機模式。但我需要基於這種模式進行分組。所以輸出應該是這樣的

Pattern  | ConnectedIDs 
----------------------------- 
2345  | 1,3,8 
3345  | 2 
5647  | 4 
1472  | 5,10 
4817  | 6 
5871  | 7,9 
----------------------------------------- 

希望你有場景..

回答

1

試試這個(Fiddle demo):

SELECT t1.Pattern, 
     Ids = REPLACE((SELECT Id AS [data()] 
      FROM Table1 t2 
      WHERE t2.Pattern = t1.Pattern 
      ORDER BY t2.Pattern 
      FOR XML PATH('') 
      ), ' ', ',') 
FROM Table1 t1 
GROUP BY Pattern; 

結果:

| PATTERN | IDS | 
|---------|-------| 
| 1472 | 5,10 | 
| 2345 | 1,3,8 | 
| 3345 |  2 | 
| 4817 |  6 | 
| 5647 |  4 | 
| 5871 | 7,9 | 
+0

感謝老闆..多數民衆贊成真棒..多數民衆贊成正是要尋找...乾杯 –

0

你可以使用這個標量值函數:

CREATE FUNCTION [dbo].[GetPatternIDs] 
(
    @pattern varchar(4), 
    @delimiter varchar(4) 
) 
RETURNS VARCHAR(8000) 
AS 
BEGIN 
    DECLARE @IDs VARCHAR(8000) 
    SELECT @IDs = COALESCE(@IDs + @delimiter, '') + CAST(Patterns.ID AS VARCHAR(10)) 
    FROM Patterns 
    WHERE [email protected] 
    ORDER By Patterns.ID 
    RETURN @IDs 
END 

與此查詢:

SELECT Pattern, 
     ConnectedIDs = dbo.GetPatternIDs(Pattern, ',') 
FROM Patterns 
GROUP BY Pattern 
ORDER BY MIN(ID) 

DEMO

+0

我試圖與之前類似的功能。但是,當噸噸這是有點慢..但上面的正確答案很好..謝謝 –