2014-03-05 78 views

回答

2

這是一個兩步過程。首先,你需要UNPIVOT列以行:

SELECT upvt.ID, Letters 
FROM T 
     UNPIVOT 
     ( Value 
      FOR Letters IN ([A], [B], [C], [D], [E], [F]) 
     ) upvt 
WHERE upvt.Value = 1; 

這給:

ID Letters 
10 A 
10 C 
10 E 
10 F 
... 

然後你需要連接的ID的從這個結果:」

WITH Unpivoted AS 
( SELECT upvt.ID, Letters 
    FROM T 
      UNPIVOT 
      ( Value 
       FOR Letters IN ([A], [B], [C], [D], [E], [F]) 
      ) upvt 
    WHERE upvt.Value = 1 
) 
SELECT u.Letters, 
     IDs = STUFF(( SELECT ', ' + CAST(u2.ID AS VARCHAR(10)) 
         FROM Unpivoted u2 
         WHERE u.Letters = u2.Letters 
         FOR XML PATH(''), TYPE 
        ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') 
FROM Unpivoted u 
GROUP BY u.Letters; 

其中給出:

Letters IDs 
A  10, 20, 50 
B  20, 40 
C  10, 20, 30, 40, 50 
D  30, 40 
E  10, 50 
F  10, 20, 40 

Example on SQL Fiddle

+0

非常感謝。我在哪裏可以指定Letter列的值。例如,A的列名是Letter_A。我怎麼能把它作爲「A」而不是結果中的列名「Letter_A」? – user3314399

+1

只需使用替換,它說'SELECT u.Letters'使用'SELECT Letters = REPLACE(u.Letters,'Letter_','')' – GarethD

+0

真棒謝謝你,最後一個問題。我如何將它插入臨時表?它不讓我這樣做,因爲查詢使用「with」。 – user3314399

0
select distinct 'A', 
(select cast(id as varchar)+',' from letters where a=1 for xml path('')) ids 
from letters where a=1 
union all 
select distinct 'B', 
(select cast(id as varchar)+',' from letters where b=1 for xml path('')) ids 
from letters where b=1 
union all 
select distinct 'C', 
(select cast(id as varchar)+',' from letters where c=1 for xml path('')) ids 
from letters where c=1 
union all 
select distinct 'D', 
(select cast(id as varchar)+',' from letters where d=1 for xml path('')) ids 
from letters where D=1 
union all 
select distinct 'E', 
(select cast(id as varchar)+',' from letters where e=1 for xml path('')) ids 
from letters where e=1 
union all 
select distinct 'F', 
(select cast(id as varchar)+',' from letters where f=1 for xml path('')) ids 
from letters where f=1 
0

這裏有兩個問題:第一,該表是不歸,讓你真正需要首先做一個額外的步驟來創建標準化數據的臨時表:

第一步:

select id, 'A' as letter 
from mytable where a=1 
union 
select id, 'B' 
from mytable where b=1 
union 
select id, 'C' 
from mytable where c=1 
union 
select id, 'D' 
from mytable where d=1 
union 
select id, 'E' 
from mytable where e=1 
union 
select id, 'F' 
from mytable where f=1 

然後,你需要將多個ID塞進一個字段。你可以用(欺騙性地命名)「For XML」來做到這一點。

喜歡的東西:

select letter, id + ', ' as [text()] 
from 
( 
select id, 'A' as letter 
from mytable where a=1 
union 
select id, 'B' 
from mytable where b=1 
union 
select id, 'C' 
from mytable where c=1 
union 
select id, 'D' 
from mytable where d=1 
union 
select id, 'E' 
from mytable where e=1 
union 
select id, 'F' 
from mytable where f=1 
) q 
group by letter 
for XML path('')) 

我認爲這是可行的。