将行数据转换为列

时间:2015-01-27 13:10:07

标签: sql oracle11g pivot oracle-sqldeveloper pivot-table

AssetName   Generation_Qtr  Cum_Actual_Gen
10001         2007 Q 2           0
2             2007 Q 3           182.21
10001         2007 Q 3           0
2             2007 Q 4           1064.49
10001         2007 Q 4            0
2             2008 Q 1           1937.18
3             2008 Q 1           1498.21
4             2008 Q 1           1291

我正在尝试编写透视查询以将行转换为列,以便我将获得以下输出

assetname   2007 q 1    2007 q 2   2007 q 3    2007 q 4
1001                     1937.18   1937.18     1937.18
2                        1937.18   182.21      1064.49   
3           1498.21
4           1291

有没有更好的方法。 我正在处理大量数据,接近50万行。

1 个答案:

答案 0 :(得分:0)

您需要使用动态SQL来透视数据。以下示例

declare @cols as varchar(100)
declare @sql as varchar(1000)

set @cols = ''
set @sql = ''

select @cols  = @cols + case when @cols = '' then '[' else ', [' end + Generation_Qtr + ']'
FROM dbo.MyData
group by Generation_Qtr
order by Generation_Qtr

select @Sql = 'SELECT *
FROM (
    select AssetName,   Generation_Qtr,  Cum_Actual_Gen 
    FROM dbo.MyData
) as s
PIVOT 
(
    SUM(Cum_Actual_Gen )
    FOR Generation_Qtr IN (' + @Cols + ')
)AS p'

exec(@Sql)