sql查询垂直显示结果

时间:2012-04-21 19:21:20

标签: sql sql-server-2008-r2 pivot pivot-without-aggregate

如何改变这个:

ID   Name    Description
1    Test1a   TestDesc1a
1    Test1b   TestDesc1b
2    Test2a   TestDesc2a
2    Test2b   TestDesc2b

进入这个:

ID   Column          1            2
1    Name          test1a       test1b
1    Description   testDesc1a   testDesc1b

4 个答案:

答案 0 :(得分:0)

你要求复杂的旋转表。在此处阅读:http://msdn.microsoft.com/en-us/library/ms177410.aspx

答案 1 :(得分:0)

您需要使用PIVOT查询。

PIVOT查询的基本讨论可以在[MSDN] [1]找到。

答案 2 :(得分:0)

这是一个棘手的问题需要解决,但指定的输出不正确/冲突。以下是您可以尝试的类似解决方案

创建样本表:

CREATE TABLE [dbo].[TestTable](
[Id] [int] NULL,
[Name] [nvarchar](50) NULL,
[Description] [nvarchar](50) NULL)

插入样本值

INSERT INTO TestTable VALUES (1,'Test1a','TestDesc1a')
INSERT INTO TestTable VALUES (2,'Test1b','TestDesc1b')
INSERT INTO TestTable VALUES (3,'Test2a','TestDesc2a')
INSERT INTO TestTable VALUES (4,'Test2b','TestDesc2b')

使用Pivot查询获得所需的输出:

SELECT  'Name' AS [Column], [1], [2],[3],[4]
FROM
(SELECT Name, id from TestTable) AS ST
PIVOT
(Max(Name) FOR ID IN ([1], [2],[3],[4])) AS PT

UNION

SELECT  'Description' AS [Column], [1], [2],[3],[4]
FROM
(SELECT  id,[Description] from TestTable) AS ST
PIVOT
(Max([Description]) FOR ID IN ([1], [2],[3],[4])) AS PT
ORDER BY [Column] DESC

<强>输出:

Column         1           2          3           4
Name           Test1a      Test1b     Test2a      Test2b
Description    TestDesc1a  TestDesc1b TestDesc2a  TestDesc2b

希望这有助于解决您的问题。

答案 3 :(得分:0)

如果您只有几列,则可以使用静态PIVOT,但我猜您将拥有2个以上的ID,因此您可能希望使用动态PIVOT这个查询。使用动态数据透视表将允许您拥有超过您提供的两个ID,它将从表中获取所有ID,然后PIVOT

create table temp
(
    id int,
    name varchar(10),
    description varchar(20)
)

insert into temp values (1, 'Test1a', 'TestDesc1a')
insert into temp values (1, 'Test1b', 'TestDesc1b')
insert into temp values (2, 'Test2a', 'TestDesc2a')
insert into temp values (2, 'Test2b', 'TestDesc2b')


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

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

set @query = 'SELECT ''Name'' as [Column], ' + @cols + ' from 
            (
                select id
                    , name
                from temp
           ) x
            pivot 
            (
                 max(name)
                for id in (' + @cols + ')
            ) p 
            UNION 
            SELECT ''Description'' as [Column], ' + @cols + ' from 
            (
                select id
                    , description
                from temp
           ) x
            pivot 
            (
                 max(description)
                for id in (' + @cols + ')
            ) p '


execute(@query)

drop table temp

结果:

Column          1             2
Description     TestDesc1b    TestDesc2b
Name            Test1b        Test2b