将SQL中的输出合并为单行

时间:2015-05-21 22:10:58

标签: sql-server

我正在尝试编写一个使用ID来选择一堆相关行的SQL查询。但是,对于每个相关项而不是单行,我想将它们连接成一行。

例如而不是:

ID    Item
1     a
2     b
1     c

我想:

ID    Item 1    Item 2    ...
1     a         c
2     b

目前我使用的是一个简单的查询,但无法弄清楚如何执行此操作:

Select
    Investigation.ID,
    Record.Item
FROM 
    Investigation
INNER JOIN 
    Record
    ON Investigation.ID = Record.Inv_Id

此查询是涉及多个连接和联合的更大的查询的一部分。最终,这将以一种希望类似于以下内容的格式转换为XML:

<investigation>
    <id>1</id>
    <name>something</name>
    <items>
        <item>a</item>
        <item>c</item>
    </items>
<investigation>
<investigation>
    <id>2</id>
    <name>something else</name>
    <items>
        <item>b</item>
    </items>
</investigation>

2 个答案:

答案 0 :(得分:1)

做了一些努力但这应该有用

DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.[Id]) 
            FROM [Investigation] c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


set @query = 'SELECT [Id], ' + @cols + ' from 
            (
                select id, item, ROW_NUMBER() over (PARTITION BY id order by item asc) as uid
                from [Investigation]
           ) x
            pivot 
            (
                MIN(item)
                for [uid] in (' + @cols + ')
            ) p '


execute(@query)

print @query

答案 1 :(得分:1)

我最终使用子查询。我确实看了你的答案Pravin但我不理解它并且无法使它工作。这是我三年前在大学时第一次深入研究SQL,所以我很生疏。这对我来说至少对单个表查询起作用:

SELECT ( SELECT * FROM ( 
    Select Investigation.ID as ID,
        (SELECT ( SELECT * FROM ( select
            Record.item
            FROM Investigation as Inv
            INNER JOIN Record
            ON Inv.ID = Record.Inv_Id
            WHERE Inv.ID = Investigations.ID
        )
        AS temp FOR xml path(''), type )
    ) AS Items
from dbo.Investigation
) AS xmlextract FOR xml path ('Investigation'), 
root('root') )AS xmlextract

它产生如下输出:

<root>
    <Investigation>
        <ID>1</ID>
        <Items>
            <item>a</item> 
            <item>c</item>
        </Items>
    </Investigation>
    <Investigation>
        <ID>2</ID>
        <Items>
            <item>b</item>
        </Items>
    </Investigation>
</root>

现在进入下一个联合问题导致我无法使用xml数据类型:P