简体   繁体   English

透视和转置

[英]Pivoting and transposing

I have the following table: 我有下表:

 |fk ID|value | val id|
 |  1  | val11|  1    |
 |  1  | val12|  2    |
 |  2  | val21|  1    |
 |  2  | val22|  2    |

I want to transpose it to: 我想将它转置为:

 | fk ID | val1Title | val2Title |
 | 1     | val11     | val12     |
 | 2     | val21     | val22     |

Ive added an ID column to the top table which is used to order so we know that val11 is in the first column because it has an id less that val12. 我已经在顶级表中添加了一个ID列,用于订购,因此我们知道val11位于第一列,因为它的id小于val12。

I have an oracle DB and I think I need to pivot. 我有一个oracle DB,我想我需要转向。 I've found a couple of articles on it (eg Transposing Table ) although it seems to be a lot of work for the pivot. 我已经找到了几篇文章(例如Transposing Table ),尽管它似乎是很多工作。 Is this the easiest way? 这是最简单的方法吗?

How can I easily transpose? 我怎样才能轻松转置? Im using Oracle 11g so am happy to use Oracle specific functions. 我正在使用Oracle 11g,所以很高兴使用Oracle特定的功能。 I've used ListAgg but that combines the columns. 我使用了ListAgg但它结合了列。 I want to columns separate though. 我想将列分开。

EDIT: The design of the original table is not normalised at the moment because this is actually the result of quite a complicated query. 编辑:原始表的设计目前尚未规范化,因为这实际上是相当复杂的查询的结果。

You can do an old-school pivot 你可以做一个老派的支点

SELECT fk_ID,
       MAX(CASE WHEN val_id=1 THEN value ELSE null END) as Val1Title,
       MAX(CASE WHEN val_id=2 THEN value ELSE null END) as Val2Title
  FROM table_name
 GROUP BY fk_ID

In 11g, you can also use the PIVOT keyword 在11g中,您还可以使用PIVOT关键字

SELECT fk_id,
       "1_VAL" as Val1Title,
       "2_VAL" as Val2Title
  FROM table_name
 PIVOT( MAX(value) as val for (val_id) in (1,2))

See this sqlfiddle for an example 请参阅此sqlfiddle以获取示例

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

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