2014-03-05 38 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('')) 

我认为这是可行的。