如何旋转表的几列并以所需的格式获取结果?

时间:2018-10-24 17:17:08

标签: sql sql-server sql-server-2012 pivot pivot-table

如何透视下表以实现所需结果。txtItem值不固定,可以是n个txtItem值。

txtItem  Rate  Revenue  Cost

   A      1200    45      30

   B      1300    55      40

   C      1400    60      30

   D      2100    55      35

预期结果:

  ColumnName      A       B      C      D

  Rate          1200    1300   1400   2100

  Revenue        45      55     60     55

  Cost           30      40     30     35

4 个答案:

答案 0 :(得分:1)

这是unvpivotpivot,因此您可以执行以下操作:

select colname, 
       max(case when txtItem = 'A' then val end) as A,
       max(case when txtItem = 'B' then val end) as B,
       max(case when txtItem = 'C' then val end) as C,
       max(case when txtItem = 'D' then val end) as D
from table t cross apply
     ( values (1, Rate, 'Rate'), (2, Revenue, 'Revenue'), (3, Cost, 'Cost') 
     ) tt(seq, val, colname)
group by seq, colname
order by seq;

答案 1 :(得分:1)

要能够转置此表,请先进行先枢轴操作,然后再进行枢轴响应

IF OBJECT_ID('tempDB..#TEMP', 'U') IS NOT NULL
DROP TABLE #TEMP
GO

CREATE TABLE #TEMP
(
    txtItem nvarchar(1),
    Rate int,
    Revenue int,
    Cost int
)

INSERT INTO #TEMP
VALUES
    ('A', 1200, 45, 30),
    ('B', 1300, 55, 40),
    ('C', 1400, 60, 30),
    ('D', 2100, 55, 35)



SELECT [ColumnName], [A],[B],[C],[D]
FROM
(
    SELECT *
    FROM #TEMP
    UNPIVOT
    (VALUE FOR ColumnName IN ([Rate],[Revenue],[Cost])
    ) UPV
) TAB
PIVOT
(
    SUM(VALUE)
    FOR txtItem IN ([A],[B],[C],[D])
) PIV

答案 2 :(得分:0)

使用不旋转和旋转

$(OBJDIR)/%.o

Demo in fiddle

答案 3 :(得分:0)

假设您的txtItem已修复,则可以先取消BelowTable的PIVOT,然后将结果PIVOT:

SELECT ColumnName, A, B, C, D
FROM BelowTable
UNPIVOT (Amount FOR ColumnName IN (Rate, Revenue, Cost)) upvt
PIVOT (SUM(Amount) FOR txtItem IN (A, B, C, D)) pvt;