oracle SQL将一些列转换为行

时间:2017-11-22 15:03:00

标签: sql oracle

我有一个如下表格,我正在尝试找到最好的查询,只将月份转换为行。

**CODE  YEAR    JAN FEB MAR**
aa      2017    1   2   3
bb      2017    4   5   6
cc      2017    7   8   9

结果是:

**CODE  YEAR    MONTH   value**
aa      2017    JAN     1
aa      2017    FEB     2
aa      2017    MAR     3
bb      2017    JAN     4
bb      2017    FEB     5
bb      2017    MAR     6
cc      2017    JAN     7
cc      2017    FEB     8
cc      2017    MAR     9

你能帮忙吗

1 个答案:

答案 0 :(得分:0)

包含数据的设置表:

Select * into #tmpTbl from (
Select 'aa' as Code,2017 as Yr, 1 as Jan,2 as Feb,3 as Mar UNION ALL
Select 'bb' as Code,2017 as Yr, 4 as Jan,5 as Feb,6 as Mar UNION ALL
Select 'cc' as Code,2017 as Yr, 7 as Jan,8 as Feb,9 as Mar) z

转换查询以生成展平结果:

SELECT Code, Yr, CrossApplied.Fld, CrossApplied.Val as Value
FROM #tmpTbl
CROSS APPLY (VALUES (JAN,'JAN'),
                (FEB,'FEB'),
                (MAR,'MAR'))
        CrossApplied (Val,Fld)

enter image description here

您的数据结构可能会更好地重新设计,以使数据更符合您的需要。这个有效,但是从这里开始实现它需要做很多工作。