MSSQL Transpose查询结果

时间:2014-06-12 12:24:23

标签: sql-server

我已经阅读了有关PIVOT和UNPIVOT的各种帖子,但我似乎无法绕过功能来完成我所追求的...我有一个查询将数据组合在一起并吐出它出:

Machine      Date      Metric1     Metric2     Metric3     Metric4
------------------------------------------------------------------
machine 1    1/1/2014      1            2         3             4  
machine 1    1/2/2014      9            5         3             7 
machine 1    1/3/2014      1            1         1             1 

但是我想让MSSQL给我这样的结果:

Desc            1/1/2014      1/2/2014      1/3/2014
----------------------------------------------------
Metric 1          1           9                  1 
Metric 2          2           5                  1
Metric 3          3           3                  1
Metric 4          4           7                  1

我尝试了枢轴并且没有成功。有关如何有效地做到这一点的任何提示?到目前为止我在SQL Fiddle中尝试的所有内容都会产生一些数据和一些空字段。

3 个答案:

答案 0 :(得分:2)

TEST_DATA

DECLARE @TABLE TABLE(Machine VARCHAR(100),[Date] Date, Metric1 INT, 
                        Metric2 INT, Metric3 INT, Metric4 INT)
INSERT INTO @TABLE VALUES
('machine 1'   ,'1/1/2014'      ,1            ,2         ,3             ,4),  
('machine 1'   ,'1/2/2014'      ,9            ,5         ,3             ,7), 
('machine 1'   ,'1/3/2014'      ,1            ,1         ,1             ,1)

查询

SELECT [Des], [2014-01-01],[2014-01-02],[2014-01-03]
FROM
(
SELECT Machine , [Date], Metric1 AS Metric, 'Metric1' AS [DES] FROM @TABLE 
UNION ALL
SELECT Machine , [Date], Metric2, 'Metric2' FROM @TABLE 
UNION ALL
SELECT Machine , [Date], Metric3, 'Metric3' FROM @TABLE 
UNION ALL
SELECT Machine , [Date], Metric4, 'Metric4' FROM @TABLE 
)t
PIVOT (SUM(Metric)
       FOR [Date]
       IN ([2014-01-01],[2014-01-02],[2014-01-03])
       )p

结果集

╔═════════╦════════════╦════════════╦════════════╗
║   Des   ║ 2014-01-01 ║ 2014-01-02 ║ 2014-01-03 ║
╠═════════╬════════════╬════════════╬════════════╣
║ Metric1 ║          1 ║          9 ║          1 ║
║ Metric2 ║          2 ║          5 ║          1 ║
║ Metric3 ║          3 ║          3 ║          1 ║
║ Metric4 ║          4 ║          7 ║          1 ║
╚═════════╩════════════╩════════════╩════════════╝

答案 1 :(得分:1)

Transpose = unpivot + pivot

SELECT Metric,[2014-01-01],[2014-01-02],[2014-01-03]
FROM MyTable
UNPIVOT(value FOR Metric IN (Metric1,Metric2,Metric3,Metric4)) t1
PIVOT(SUM(value) FOR Date IN ([2014-01-01],[2014-01-02],[2014-01-03])) t2

答案 2 :(得分:0)

感谢您的回复,幸运的是我会在询问后立即找到解决方案(尽可能接近)。对于其他可能有同样问题的人来说,这是最终结果的SQL小提琴。

http://sqlfiddle.com/#!3/6be41