SQL - 为unpivoted数据创建属性输出

时间:2017-10-10 15:28:49

标签: sql sql-server pivot unpivot cross-apply

我有一个如下所示的数据集:

Position_Date   Portfolio   Country   Weight   BM Weight
2017-09-30      Port1       Mexico    0.2      0.0
2017-09-30      Port1       Mexico    0.1      0.1
2017-09-30      Port1       USA       0.2      0.2
2017-09-30      Port1       USA       0.3      0.1

我想使用SQL查询将此存储的数据集转换为以下输出:

Portfolio_Date  Portfolio  Dimension        Dimension_Value  Measure    Measure_Value
2017-09-30      Port1      Country          Mexico           Weight     0.3
2017-09-30      Port1      Country          Mexico           BM Weight  0.1
2017-09-30      Port1      Country          USA              Weight     0.5
2017-09-30      Port1      Country          USA              BM Weight  0.3
2017-09-30      Port1      Portfolio        Country          Weight     0.8
2017-09-30      Port1      Portfolio        Country          BM Weight  0.4

我想知道创建数据集的有效性是什么?我是否必须将数据PIVOT然后UNPIVOT它来创建我的最终数据集?或者是否有另一种方法使用CROSS APPLY和我可以利用的GROUP BY,我在这个论坛的其他帖子中看到过?

由于

1 个答案:

答案 0 :(得分:1)

这个问题比我初想的要复杂得多。在进行聚合之后我会做一些事情:

select t.Portfolio_Date, t.Portfolio,
       v.*
from (select t.Portfolio_Date, t.Portfolio,
             coalesce(country, 'Country') as dimension_value,  -- coalesce is a shortcut for getting the aggregated row
             coalesce(country, 'Portfolio') as dimension,
             sum(weight) as weight, sum(bm_weight) as bm_weight
      from t
      group by grouping sets ( (t.Portfolio_Date, t.Portfolio, country), (t.Portfolio_Date, t.Portfolio) )
     ) t outer apply
     (values (dimension, dimension_value, 'Weight', weight),
             (dimension, dimension_value, 'BM Weight', bm_weight)
     ) v(dimension, dimension_value, measure, measure_value);