2

如何转换这个:

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

4 回答 4

0

You need to use a PIVOT query.

A basic discussion of PIVOT queries can be found at [MSDN][1].

于 2012-04-21T19:53:56.717 回答
0

您要求复杂的数据透视表。在这里阅读:http: //msdn.microsoft.com/en-us/library/ms177410.aspx

于 2012-04-21T19:39:13.870 回答
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

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

于 2012-04-21T21:09:41.797 回答
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
于 2012-05-02T15:57:06.077 回答