2017-10-10 85 views
1

我有一个数据集看起来像下面这样:SQL - 创建属性输出逆转置数据

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 

我想知道为什么要创建数据集有效吗?我是否需要将数据插入才可以将它释放以创建我的最终数据集?或者有另一种方法使用CROSS APPLY和GROUP BY,我可以在这个论坛的其他帖子中看到这些使用情况?

谢谢

回答

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); 
+0

感谢在正确的方向@Gordon Linoff –

+0

只是想知道一点,如果你能向我解释,你对COALESCE是用于获取汇总行的快捷方式有何评论? @Gordon Linoff –

+1

@chrissyp。 。 。 'grouping sets'返回聚合行的NULL值。当然,原来的键可能已经有了'NULL',所以它是一个hacky(但非常方便)的解决方案。正确的方法是使用'grouping()',但这需要一个'case'。 –