简体   繁体   English

将行透视为列 Oracle SQL

[英]Pivoting rows into columns Oracle SQL

I am currently working on a table where the format of the table is something like this (all the columns are of type VARCHAR except the INSERTDATE column which is of type DATE):我目前正在处理一个表格,其中表格的格式是这样的(所有列都是 VARCHAR 类型,除了 DATE 类型的 INSERTDATE 列):

INSERTDATE | ID   | PROPERTYNAME  | PROPERTYVALUE
----------------------------------------------
date1      | 1000 | ItemNumber    | 20.1A14
date1      | 1000 | ItemRev       | 2
date1      | 1000 | BarCodeNumber | 3854981
date2      | 1001 | ItemNumber    | 20.1B24
date2      | 1001 | ItemRev       | 1
date2      | 1001 | BarCodeNumber | 3856539

What I want to do is to convert all PROPERTYNAME column values into separate columns with all of their respective PROPERTYVALUE column values into their respective columns, something like this:我想要做的是将所有 PROPERTYNAME 列值转换为单独的列,并将所有各自的 PROPERTYVALUE 列值转换为各自的列,如下所示:

INSERTDATE | ID   | ItemNumber | ItemRev | BarCodeNumber
-------------------------------------------------------
date1      | 1000 | 20.1A14    | 2       | 3854981
date2      | 1001 | 20.1B24    | 1       | 3856539

I have been trying to solve this problem for days without any result.我几天来一直试图解决这个问题,但没有任何结果。 I looked up everything on Pivot on the internet but none of the examples match my own needs.我在互联网上的 Pivot 上查找了所有内容,但没有一个示例符合我自己的需求。 I am not much familiar with Pivot in SQL so it would really be helpful if anyone can help me figure out how to use it to solve my problem.我对 SQL 中的 Pivot 不太熟悉,所以如果有人能帮助我弄清楚如何使用它来解决我的问题,那真的会很有帮助。

If you know the columns you want, you can use conditional aggregation:如果您知道所需的列,则可以使用条件聚合:

select insertdate, id,
       max(case when PROPERTYNAME = 'ItemNumber' then propertyvalue end) as ItemNumber,
       max(case when PROPERTYNAME = 'ItemRev' then propertyvalue end) as ItemRev,
       max(case when PROPERTYNAME = 'BarCodeNumber' then propertyvalue end) as BarCodeNumber
from t
group by insertdate, id;

If you don't know all the properties up-front, then you need to construct the query dynamically as a string and use execute immediate .如果您事先不知道所有属性,那么您需要将查询动态构造为字符串并使用execute immediate

The use case is a right candidate for PIVOT and you can use it perfectly here.该用例是PIVOT的正确候选者,您可以在这里完美地使用它。

Assuming you are using Oracle as your database the query will look like,假设您使用Oracle作为数据库,查询将如下所示,

select insertdate,id,ItemNumber,ItemRev,BarCodeNumber
  from mytable
pivot
(
 max(propertyvalue)
 for propertyname in ('ItemNumber' as ItemNumber
                     ,'ItemRev' ItemRev
                     ,'BarCodeNumber' BarCodeNumber)
)
order by insertdate;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM