这是否可能与Unpivot?

时间:2014-07-08 20:02:06

标签: sql view pivot unpivot

我有一张这样的表:

ForeignKeyA,ForeignKeyB,Before1,After1,Before2,After2,... Before(n),After(n)

我需要能够创建一个视图,将此表格忽略为:

ForeignKeyA,ForeignKeyB,Year,Before,After

其中Year是Before / After列的迭代。

编辑:我现在已经达到了这一点,但我不确定如何将年份分成它自己的专栏。

    SELECT [f_lForiegnKey], [f_lAnalysisVariableKey], dBefore, dAfter, szBefore,     szAfter
    FROM 
    (SELECT [f_lForiegnKey], [f_lAnalysisVariableKey], [dBefore01], [dAfter01],   [szBefore01], [szAfter01],
    [dBefore02], [dAfter02],[szBefore02], [szAfter02],
    [dBefore03], [dAfter03],[szBefore03], [szAfter03],
    [dBefore04], [dAfter04],[szBefore04], [szAfter04],
    [dBefore05], [dAfter05],[szBefore05], [szAfter05]

    FROM [dbo].[A_STRATS_V]) p
    UNPIVOT
    (dBefore FOR dBeforex IN ([dBefore01], [dBefore02], [dBefore03], [dBefore04],     [dBefore05])) AS U1

    UNPIVOT
    (dAfter FOR dAfterx IN ([dAfter01], [dAfter02], [dAfter03], [dAfter04], [dAfter05])) AS U2

    UNPIVOT
    (szBefore FOR szBeforex IN ([szBefore01], [szBefore02], [szBefore03], [szBefore04], [szBefore05])) AS U3

    UNPIVOT
    (szAfter FOR szAfterx IN ([szAfter01], [szAfter02], [szAfter03], [szAfter04], [szAfter05])) AS U4

    WHERE RIGHT(dBeforex, 1) = RIGHT(dAfterx, 1) 

    AND RIGHT(dBeforex, 1) = RIGHT(szBeforex, 1) 

    AND RIGHT(dBeforex, 1) = RIGHT(szAfterx, 1);
    GO

我需要截断每组的数字并将其放在自己的列中。这可能吗?

感谢。

1 个答案:

答案 0 :(得分:-1)

这是可能的。我无法挖掘我的代码,但这里有类似的东西

unpivot with dynamic columns plus column names

基本上,你从sysobjects中获取列名并将动态sql写入unpivot。