SQL Query选择特定的列值并将它们连接起来

时间:2014-03-05 16:54:56

标签: sql sql-server database sql-server-2008 tsql

有人可以帮我实现这个查询:我需要为每个值为1的字母提供所有ID:

enter image description here

3 个答案:

答案 0 :(得分:2)

这是一个两步过程。首先,您需要将列拆分为行:

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

答案 1 :(得分: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

答案 2 :(得分: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(''))

我认为这样可行。