在 Oracle 中动态地将行转换为列

发布于 2024-12-09 13:28:30 字数 729 浏览 3 评论 0原文

我有以下名为 _kv 的 Oracle 10g 表:

select * from _kv

ID       K       V
----     -----   -----
  1      name    Bob
  1      age     30
  1      gender  male
  2      name    Susan
  2      status  married

我想使用普通 SQL(不是 PL/SQL)将键转换为列,以便生成的表看起来像这样:

ID       NAME    AGE    GENDER  STATUS
----     -----   -----  ------  --------
  1      Bob      30     male 
  2      Susan                   married
  • 查询应该具有与唯一的列一样多的列 <表中存在 code>K(没有那么多)
  • 在运行查询之前无法知道可能存在哪些列。
  • 我试图避免运行初始查询以编程方式构建最终查询。
  • 空白单元格可能是空值或空字符串,这并不重要。
  • 我使用的是 Oracle 10g,但 11g 解决方案也可以。

当您知道旋转列的名称时,有很多示例可供参考,但我就是找不到适用于 Oracle 的通用旋转解决方案。

谢谢!

I have the following Oracle 10g table called _kv:

select * from _kv

ID       K       V
----     -----   -----
  1      name    Bob
  1      age     30
  1      gender  male
  2      name    Susan
  2      status  married

I'd like to turn my keys into columns using plain SQL (not PL/SQL) so that the resulting table would look something like this:

ID       NAME    AGE    GENDER  STATUS
----     -----   -----  ------  --------
  1      Bob      30     male 
  2      Susan                   married
  • The query should have as many columns as unique Ks exist in the table (there aren't that many)
  • There's no way to know what columns may exist before running the query.
  • I'm trying to avoid running an initial query to programatically build the final query.
  • The blank cells may be nulls or empty strings, doesn't really matter.
  • I'm using Oracle 10g, but an 11g solution would also be ok.

There are a plenty of examples out there for when you know what your pivoted columns may be called, but I just can't find a generic pivoting solution for Oracle.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

¢好甜 2024-12-16 13:28:30

Oracle 11g 提供了一个PIVOT 操作来完成您想要的操作。

Oracle 11g 解决方案

select * from
(select id, k, v from _kv) 
pivot(max(v) for k in ('name', 'age', 'gender', 'status')

(注意:我没有 11g 的副本来测试它,因此我尚未验证其功能)

我从以下位置获得了此解决方案:http://orafaq.com/wiki/PIVOT

编辑 -- 数据透视 xml 选项(也是 Oracle 11g)
显然,当您不知道可能需要的所有可能的列标题时,还有一个 pivot xml 选项。 (请参阅页面底部附近的 XML 类型 部分,位于 http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html

select * from
(select id, k, v from _kv) 
pivot xml (max(v)
for k in (any) )

(注意:和以前一样,我没有11g 的副本来测试它,所以我还没有验证其功能)

Edit2: 更改了 pivot中的 v >pivot xml 语句到 max(v) 因为它应该按照评论之一中提到的那样进行聚合。我还添加了 in 子句,该子句对于 pivot 来说不是可选的。当然,必须在 in 子句中指定值违背了完全动态的数据透视表/交叉表查询的目标,而这正是该问题发布者的愿望。

Oracle 11g provides a PIVOT operation that does what you want.

Oracle 11g solution

select * from
(select id, k, v from _kv) 
pivot(max(v) for k in ('name', 'age', 'gender', 'status')

(Note: I do not have a copy of 11g to test this on so I have not verified its functionality)

I obtained this solution from: http://orafaq.com/wiki/PIVOT

EDIT -- pivot xml option (also Oracle 11g)
Apparently there is also a pivot xml option for when you do not know all the possible column headings that you may need. (see the XML TYPE section near the bottom of the page located at http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html)

select * from
(select id, k, v from _kv) 
pivot xml (max(v)
for k in (any) )

(Note: As before I do not have a copy of 11g to test this on so I have not verified its functionality)

Edit2: Changed v in the pivot and pivot xml statements to max(v) since it is supposed to be aggregated as mentioned in one of the comments. I also added the in clause which is not optional for pivot. Of course, having to specify the values in the in clause defeats the goal of having a completely dynamic pivot/crosstab query as was the desire of this question's poster.

场罚期间 2024-12-16 13:28:30

为了处理可能存在多个值的情况(示例中为 v),我使用 PIVOT 和 LISTAGG :

SELECT * FROM
(
  SELECT id, k, v
  FROM _kv 
)
PIVOT 
(
  LISTAGG(v ,',') 
  WITHIN GROUP (ORDER BY k) 
  FOR k IN ('name', 'age','gender','status')
)
ORDER BY id;

由于您需要动态值,因此请使用动态 SQL 并传递在调用数据透视语句之前对表数据运行 select 确定的值。

To deal with situations where there are a possibility of multiple values (v in your example), I use PIVOT and LISTAGG:

SELECT * FROM
(
  SELECT id, k, v
  FROM _kv 
)
PIVOT 
(
  LISTAGG(v ,',') 
  WITHIN GROUP (ORDER BY k) 
  FOR k IN ('name', 'age','gender','status')
)
ORDER BY id;

Since you want dynamic values, use dynamic SQL and pass in the values determined by running a select on the table data before calling the pivot statement.

半世蒼涼 2024-12-16 13:28:30

碰巧有一个关于枢轴的任务。下面是我刚刚在 11g 上测试的结果:

select * from
(
  select ID, COUNTRY_NAME, TOTAL_COUNT from ONE_TABLE 
) 
pivot(
  SUM(TOTAL_COUNT) for COUNTRY_NAME in (
    'Canada', 'USA', 'Mexico'
  )
);

Happen to have a task on pivot. Below works for me as tested just now on 11g:

select * from
(
  select ID, COUNTRY_NAME, TOTAL_COUNT from ONE_TABLE 
) 
pivot(
  SUM(TOTAL_COUNT) for COUNTRY_NAME in (
    'Canada', 'USA', 'Mexico'
  )
);
-小熊_ 2024-12-16 13:28:30

首先,需要再次解析使用pivot xml动态透视。我们还有另一种方法来做到这一点,即将列名存储在变量中并将它们传递到动态 sql 中,如下所示。

考虑我们有一个如下表。

中的值显示为列名称,以及这些列中 QTY 中的值,那么我们可以使用下面的代码。

declare
  sqlqry clob;
  cols clob;
begin
  select listagg('''' || YR || ''' as "' || YR || '"', ',') within group (order by YR)
  into   cols
  from   (select distinct YR from EMPLOYEE);


  sqlqry :=
  '      
  select * from
  (
      select *
      from EMPLOYEE
  )
  pivot
  (
    MIN(QTY) for YR in (' || cols  || ')
  )';

  execute immediate sqlqry;
end;
/

结果

在此处输入图像描述

First of all, dynamically pivot using pivot xml again needs to be parsed. We have another way of doing this by storing the column names in a variable and passing them in the dynamic sql as below.

Consider we have a table like below.

enter image description here

If we need to show the values in the column YR as column names and the values in those columns from QTY, then we can use the below code.

declare
  sqlqry clob;
  cols clob;
begin
  select listagg('''' || YR || ''' as "' || YR || '"', ',') within group (order by YR)
  into   cols
  from   (select distinct YR from EMPLOYEE);


  sqlqry :=
  '      
  select * from
  (
      select *
      from EMPLOYEE
  )
  pivot
  (
    MIN(QTY) for YR in (' || cols  || ')
  )';

  execute immediate sqlqry;
end;
/

RESULT

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文