Oracle Query - 将列值作为多个值的列标题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Oracle Query - 将列值作为多个值的列标题相关的知识,希望对你有一定的参考价值。
我有下表
Product Code Value time
ABC ASK 15 31-AUG-18
ABC BID 18 31-AUG-18
ABC MID 15 31-AUG-18
ABC ASK 11 31-AUG-18
ABC BID 12 31-AUG-18
ABC MID 10 31-AUG-18
ABC ASK 1.3 31-AUG-18
ABC BID 1.8 31-AUG-18
ABC MID 1.5 31-AUG-18
我想输出为,
Product ASK BID MID Date
ABC 15 18 15 31-AUG-18
ABC 11 12 10 31-AUG-18
ABC 1.3 1.8 1.5 31-AUG-18
我尝试使用pivot,但它总结了所有不是所需输出的值。我能得到这样的东西,但这不是我想要的,
Product ASK BID MID Date
ABC 27.3 31.8 26.5 31-AUG-18
任何建议都会非常有帮助。
答案
使用ROW_NUMBER
分析函数为每个组的每个代码提供唯一标识符:
Oracle 11g R2架构设置:
CREATE TABLE table_name ( Product, Code, Value, time ) AS
SELECT 'ABC', 'ASK', 15.0, DATE '2018-08-31' FROM DUAL UNION ALL
SELECT 'ABC', 'BID', 18.0, DATE '2018-08-31' FROM DUAL UNION ALL
SELECT 'ABC', 'MID', 15.0, DATE '2018-08-31' FROM DUAL UNION ALL
SELECT 'ABC', 'ASK', 11.0, DATE '2018-08-31' FROM DUAL UNION ALL
SELECT 'ABC', 'BID', 12.0, DATE '2018-08-31' FROM DUAL UNION ALL
SELECT 'ABC', 'MID', 10.0, DATE '2018-08-31' FROM DUAL UNION ALL
SELECT 'ABC', 'ASK', 1.3, DATE '2018-08-31' FROM DUAL UNION ALL
SELECT 'ABC', 'BID', 1.8, DATE '2018-08-31' FROM DUAL UNION ALL
SELECT 'ABC', 'MID', 1.5, DATE '2018-08-31' FROM DUAL;
查询1:
SELECT Product,
ask,
bid,
mid,
time
FROM (
SELECT t.*,
ROW_NUMBER() OVER ( PARTITION BY Product, Code, time ORDER BY ROWNUM ) AS rn
FROM table_name t
)
PIVOT ( MAX( value ) FOR Code IN (
'ASK' AS ask,
'BID' AS bid,
'MID' AS mid
) )
ORDER BY product, time, rn
| PRODUCT | ASK | BID | MID | TIME |
|---------|-----|-----|-----|----------------------|
| ABC | 15 | 18 | 15 | 2018-08-31T00:00:00Z |
| ABC | 11 | 12 | 10 | 2018-08-31T00:00:00Z |
| ABC | 1.3 | 1.8 | 1.5 | 2018-08-31T00:00:00Z |
理想情况下,您应该有另一列来包含排序,因为如果Oracle以不同的顺序读取行(或者如果启用了行移动),则不能保证使用ROWNUM
以一致的顺序给出行。
以上是关于Oracle Query - 将列值作为多个值的列标题的主要内容,如果未能解决你的问题,请参考以下文章