Oracle查询-将列值作为多个值的列标题

时间:2018-09-03 19:29:39

标签: sql oracle pivot

我有下表

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

我使用数据透视表尝试了此操作,但它会将所有值加起来,而不是所需的输出。我可以得到这样的东西,但这不是我们想要的,

Product ASK   BID   MID   Date
ABC     27.3  31.8  26.5  31-AUG-18

任何建议都会很有帮助。

1 个答案:

答案 0 :(得分:5)

使用ROW_NUMBER分析函数为每组代码赋予唯一的标识符:

SQL Fiddle

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

Results

| 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会以一致的顺序提供行。 / p>