Oracle sql 中的 PIVOT

Posted

技术标签:

【中文标题】Oracle sql 中的 PIVOT【英文标题】:PIVOT in Oracle sql 【发布时间】:2015-07-15 12:05:40 【问题描述】:

我已经写了一个如下所示的查询

    SELECT DISTINCT SBPC1.BATCH_ID AS BATCH_ID,
  Sbpc1.Registration_Id        AS Registration_Id,
  Submtd_Val_Code.Submtd_Val_Cd,
  Submtd_Val_Code.Submtd_Val_Amount ,
  Submtd_Val_Code.Submtd_Bill_Processing_Cd_Seq
  --Submtd_Val_Code.rownumber
  --rownum
FROM TEMPORARY_EXTRACT_BASE PARTITION (TEMPORARY_EXTRACT_BA_815771) TEB,
  Submtd_Bill_Processing_Cd Sbpc1 ,
  (SELECT Sbpc1.Batch_Id  AS Batch_Id,
    Sbpc1.Registration_Id AS Registration_Id,
    Submtd_Val_Cd,
    SBPC1.SUBMTD_VAL_AMOUNT,
    Sbpc1.Submtd_Bill_Processing_Cd_Seq,
    rownum AS rownumber
  FROM Temporary_Extract_Base Partition (Temporary_Extract_Ba_815771) Teb,
    Submtd_Bill_Processing_Cd Sbpc1
  WHERE SBPC1.BATCH_ID     = TEB.EXTRACT_BATCH_ID
  AND SBPC1.REGISTRATION_ID=TEB.REGISTRATION_ID
  AND TEB.BATCH_ID         = 815771
  AND SBPC1.BATCH_ID      IN
    (SELECT BATCH_ID
    FROM PBLSH_BATCH_INCLUSION
    WHERE DATA_PBLSH_ID IN
      (SELECT DATA_PBLSH_ID FROM Batch WHERE Batch_Id = 815771
      )
    )
  AND Upper(Sbpc1.Submtd_Val_Cd) <> 'NOT AVAILABLE'
  AND Upper(Sbpc1.Submtd_Val_Cd) <> 'NOT SUPPLIED'
  ORDER BY TEB.REGISTRATION_ID,
    Sbpc1.SUBMTD_BILL_PROCESSING_CD_SEQ
  )Submtd_Val_Code
WHERE SBPC1.BATCH_ID     = TEB.EXTRACT_BATCH_ID
AND SBPC1.REGISTRATION_ID=TEB.REGISTRATION_ID
AND TEB.BATCH_ID         = 815771
AND SBPC1.BATCH_ID      IN
  (SELECT BATCH_ID
  FROM PBLSH_BATCH_INCLUSION
  WHERE DATA_PBLSH_ID IN
    (SELECT DATA_PBLSH_ID FROM BATCH WHERE Batch_Id = 815771
    )
  )
AND Submtd_Val_Code.Registration_Id =Teb.Registration_Id
ORDER BY SBPC1.BATCH_ID,
  SBPC1.REGISTRATION_ID,
  Submtd_Val_Code.SUBMTD_BILL_PROCESSING_CD_SEQ;

它产生的输出为:

对于每个 Registration_id,我需要如下输出:

前 5 个有效值应加载到相应的列。如果不使用存储过程,通过单条select语句实现会更好。

任何人请帮忙...提前谢谢!!!

【问题讨论】:

【参考方案1】:

只有当您选择的值列表中有任何聚合函数时,才能使用 Pivot:

使用 pivot 的例子是这样的:

SELECT *
FROM   (SELECT product_code, quantity
        FROM   pivot_test)
PIVOT  (SUM(quantity) AS sum_quantity FOR (product_code) IN ('A' AS a, 'B' AS b, 'C' AS c));

如果您可以拥有一个聚合函数,那么您可以尝试将整个 select 语句作为一个 cte(公共表表达式),然后将该表与 pivot 方法一起使用。

示例:

with cte as 
(----- your sql statement--- )
select * from cte
pivot (sum(val) for name in ( select name from cte ) );

【讨论】:

是的,pivot 仅用于此目的。您可以尝试如下:code 与 cte 为 (SELECT DISTINCT SBPC1.BATCH_ID AS BATCH_ID, Sbpc1.Registration_Id AS Registration_Id, Submtd_Val_Code.Submtd_Val_Cd, Submtd_Val_Code.Submtd_Val_Amount, Submtd_Val_Code.Submtd_Bill_Processing_Cd_Seq) 选择您的查询* from cte pivot (sum(Registration_Id) for Registration_Id in (46057007,46057008,....)) code

以上是关于Oracle sql 中的 PIVOT的主要内容,如果未能解决你的问题,请参考以下文章

oracle中的sql求总分前三名

sql Oracle - 检查Oracle中的租用对象

如何清除oracle中的执行sql记录在日志里面的的记录

oracle sql语句中的替换问题

从 SQL Server 转换 Oracle 中的更新 SQL

关于oracle存储过程中的sql拼接,大神进!!!