sql将列数据转换为行

时间:2018-02-25 22:47:32

标签: sql pivot

我正在使用SQL工作台中的表。

我有一张人口数据表,如下所示(为了方便,人口数量减少):

State   2010   2011  2012  2013  2014  2015
Alaska    5     8     10    13    15    19

我想将此表转换为如下所示的表:

State    Year   Estimate
Alaska    2010     5
Alaska    2011     8
Alaska    2012     10
Alaska    2013     13
Alaska    2014     15
Alaska    2015     19

我需要做什么声明才能实现这一目标?

谢谢, 盖瑞特

1 个答案:

答案 0 :(得分:0)

Union all是一种通用方法:

select state, '2010' as year, "2010" as Estimate from t
union all
select state, '2011' as year, "2011" as Estimate from t
union all
select state, '2012' as year, "2012" as Estimate from t
union all
select state, '2013' as year, "2013" as Estimate from t
union all
select state, '2014' as year, "2014" as Estimate from t
union all
select state, '2015' as year, "2015" as Estimate from t;

还有其他方法更有效(特别是对于较大的表)。我首选使用横向联接(使用lateralapply关键字)。 SQL还为unpivoting提供了非常具体的语法。