SQL Pivot Rows到列

时间:2016-01-10 23:17:38

标签: sql pivot rows large-data

认为这很容易,但我遇到了麻烦。我需要使用100,000多行来旋转(或取消忽略)一个表(称为da_LMP_downloads)。我从这开始:table_before

在:

市场日|节点| Node_Type | LMP_Value | HE1 | HE2 | HE 3 | ....... | HE24 |

10/1/12 | AEC |界面| LMP | 17.82 | 16.44 | 16.45

10/1/12 | AEC |界面| MCC | .14 | .16 | 0.62

10/1/12 | AEC |界面| MLC | -.38 | -.34 | 0.34

但在枢轴之后需要它看起来像这样:table_after

后:

Market_Day |节点|他| daLMP | daMCC | daMLC

10/1/12 | AEC | 1 | 17.82 | .14 | -.38

10/1/12 | AEC | 2 | 16.44 | .16 | -.34

10/1/12 | AEC | 3 | 16.45 | .62 | 0.34

1 个答案:

答案 0 :(得分:1)

如果您的dbms是SQL Server,那么您可以使用CROSS APPLY和VALUES来实现" unpivot"部分,但你还需要一个小的"枢轴"操作也出现,并且GROUP BY将起作用。请注意,这仅适用于SQL Server,其他数据库对于unpivot / pivot具有非常不同的语法。

/* input looks like this...
Market_Day Node Node_Type LMP_Value HE1   HE2   .... HE24
2012-10-01 AEC Interface  LMP       17.82 16.44 .... 19.77
*/
SELECT
      sq.Market_Day
    , sq.Node
    , sq.Node_Type
    , sq.HE
    , MAX(sq.daLMP) AS daLMP
    , MAX(sq.daMCC) AS daMCC
    , MAX(sq.daMLC) AS daMLC
FROM (
      SELECT
            t.Market_Day
          , t.Node
          , t.Node_Type
          , ca.HE
          , CASE WHEN LMP_Value = 'LMP' THEN ca.val END AS daLMP
          , CASE WHEN LMP_Value = 'MCC' THEN ca.val END AS daMCC
          , CASE WHEN LMP_Value = 'MLC' THEN ca.val END AS daMLC
      FROM Table1 t
            CROSS APPLY (
                  VALUES
                        (1, HE1)
                      , (2, HE2)
                      , (3, HE3)
                      , (4, HE4)
                      , (5, HE5)
                      , (6, HE6)
                      , (7, HE7)
                      , (8, HE8)
                      , (9, HE9)
                      , (10, HE10)
                      , (11, HE11)
                      , (12, HE12)
                      , (13, HE13)
                      , (14, HE14)
                      , (15, HE15)
                      , (16, HE16)
                      , (17, HE17)
                      , (18, HE18)
                      , (19, HE19)
                      , (20, HE20)
                      , (21, HE21)
                      , (22, HE22)
                      , (23, HE23)
                      , (24, HE24)
                        ) AS ca (HE, val)
    ) AS sq
GROUP BY
      sq.Market_Day
    , sq.Node
    , sq.Node_Type
    , sq.HE

注意TSQL实际上确实有" pivot"和" unpivot"运算符,但我发现使用交叉应用/值可以更有效,更简单地实现。