将列转置为行

时间:2015-07-30 09:24:13

标签: sql-server tsql pivot

我有一个表格的结果集,如下图所示:

enter image description here

由以下查询返回:

SELECT [id],[siteId],[variableId],[qualifierId],[value],[valueDate],[insertDate],[insertUserID] ,[deleteDate],[deleteUserId],[dataStatus] FROM MyTable

我想按照其他图片进行转置:

enter image description here

我试图关注PIVOT样本,但无法达到结果。这是我的尝试(我没有包括所有列):

SELECT  [1281] AS q1, [1282] AS q2, [1283] AS q3, [1284] AS q4, [1285] AS q5, [1286] AS q6, [1287] AS q7, [1288] AS q8, [1289] AS q9
FROM 
(
SELECT  id, qualifierId, value, insertDate FROM BADMEntries where variableId=1000) p
PIVOT
(
    MAX(value)
    FOR qualifierId IN
    ( [1281] , [1282], [1283], [1284], [1285], [1286], [1287], [1288], [1289] )
) AS pvt

但没有用,因为这是我得到的结果: enter image description here

错误在哪里?! 谢谢,迪戈

1 个答案:

答案 0 :(得分:0)

从您的子查询中删除id列,即使您没有在PIVOT子句中使用它,也不会在最终SELECT语句中将其用于分组:

SELECT  [1281] AS q1, [1282] AS q2, [1283] AS q3, [1284] AS q4, [1285] AS q5, [1286] AS q6, [1287] AS q7, [1288] AS q8, [1289] AS q9
FROM 
(
SELECT  qualifierId, value, insertDate FROM BADMEntries where variableId=1000) p
PIVOT
(
    MAX(value)
    FOR qualifierId IN
    ( [1281] , [1282], [1283], [1284], [1285], [1286], [1287], [1288], [1289] )
) AS pvt

说明:

假设我有下表:

DECLARE @DataSource TABLE
(
    [RecordID] TINYINT
   ,[Team] VARCHAR(12)
   ,[MatchID] TINYINT
   ,[Score] TINYINT
);

INSERT INTO @DataSource ([RecordID], [Team], [MatchID], [Score])
VALUES (1, 'A', 1, 50)
      ,(2, 'A', 2, 10)
      ,(3, 'B', 1, 20)
      ,(4, 'B', 2, 40)
      ,(5, 'B', 3, 70);

enter image description here

我想在PIVOT列之前制作[MatchID]并撰写以下查询:

SELECT *
FROM 
(
    SELECT *
    FROM @DataSource
) DS
PIVOT
(
    MAX([Score]) FOR [MatchID] IN ([1], [2], [3])
) PVT;

我得到以下结果(与您类似):

enter image description here

问题由RecordID列“引起”,因为它是唯一的,结果是由它组成的。所以,要解决这个问题,我需要删除它:

SELECT *
FROM 
(
    SELECT [Team]
          ,[MatchID]
          ,[Score]
    FROM @DataSource
) DS
PIVOT
(
    MAX([Score]) FOR [MatchID] IN ([1], [2], [3])
) PVT;

一切正常:

enter image description here