首页 > 解决方案 > SQL 列名作为行值

问题描述

我有一个包含“区域”、“目标”和“实际”列的表格,如下所示。

地区 目标 实际的
一个 10 1
20 2

我想用我的查询更改这个表,以便目标列和实际列在行中,如下所示。

地区 类型 数量
一个 目标 10
一个 实际的 1
目标 20
实际的 2

我应该如何为此准备查询或应该使用哪种方式?提前致谢。

标签: sqloraclepivot

解决方案


您可以为此使用 UNION:

select region, 'Target' as type, target as amount
from the_table
union all
select region, 'Actual' as type, actual
from the_table
order by region, type desc

另一种选择是使用横向连接从列中构造两行:

select t.region, x.*
from the_table t
  cross join lateral (
    values ('Target', target), ('Actual', actual)
  ) as x(type, amount)
order by t.region, x.type desc;  

这两个查询都是 100% 的标准 ANSI SQL。然而,并非所有数据库产品都支持横向连接或VALUES类似的子句。


推荐阅读