【问题标题】:SQL Column Name as Row ValueSQL 列名作为行值
【发布时间】:2021-09-22 11:52:57
【问题描述】:

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

Region Target Actual
A 10 1
B 20 2

我想用我的查询更改此表,以便目标列和实际列位于如下行中。

Region Type Amount
A Target 10
A Actual 1
B Target 20
B Actual 2

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

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。

标签: sql oracle pivot


【解决方案1】:

您可以为此使用 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 子句。

【讨论】:

    【解决方案2】:

    您可以使用UNPIVOT 对表格进行单一访问,该表格完全符合描述:

    select /*+ gather_plan_statistics */ *
    from t
    unpivot(
      Amount for Type_ in (
        Target as 'Target'
        , Actual as 'Actual'
      )
    )
    
    地区 |类型_ |数量 :----- | :----- | -----: 一个 |目标 | 10 一个 |实际 | 1 乙|目标 | 20 乙|实际 | 2
    |计划表输出 | | :------------------------------------------------ ---------------------------------------------- | | SQL_ID 9rr5wa2yjxf42,子编号 0 | | -------------------------------------- | | select /*+ gather_plan_statistics */ * from t unpivot( Amount for | |输入(目标为“目标”,实际为“实际”))| | | |计划哈希值:605266837 | | | | -------------------------------------------------- ---------------------------------------------- | | |身份证 |操作 |姓名 |开始 |电子行 | A-行 |时间 |缓冲器 |阅读 | | | -------------------------------------------------- ---------------------------------------------- | | | 0 |选择声明 | | 1 | | 4 |00:00:00.01 | 2 | 1 | | | |* 1 |查看 | | 1 | 4 | 4 |00:00:00.01 | 2 | 1 | | | | 2 |未透视 | | 1 | | 4 |00:00:00.01 | 2 | 1 | | | | 3 |表访问已满| T | 1 | 2 | 2 |00:00:00.01 | 2 | 1 | | | -------------------------------------------------- ---------------------------------------------- | | | |谓词信息(由操作 id 标识):| | -------------------------------------------------- - | | | | 1 - 过滤器(“unpivot_view_005”。“AMOUNT”不为空)| | |

    db小提琴here

    【讨论】:

      猜你喜欢
      • 2010-11-18
      • 1970-01-01
      • 2022-09-24
      • 1970-01-01
      • 1970-01-01
      • 2012-10-10
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      相关资源
      最近更新 更多