如何转换它:
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
您要求复杂的数据透视表。在此处阅读以下内容:http://msdn.microsoft.com/en-us/library/ms177410.aspx
您需要使用 PIVOT 查询。
有关 PIVOT 查询的基本讨论,请参见 [MSDN][1]。
这是一个棘手的问题,但是指定的输出不正确/冲突。以下是您可以尝试的类似解决方案
示例表创建:
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')
使用透视查询以获取所需的输出:
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
希望这有助于解决您的问题。
如果您只有几列,则可以使用静态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