在源表中的多个列上进行透视

时间:2019-10-23 11:37:52

标签: oracle oracle-sqldeveloper

我有一个查询,其中在一个列上进行旋转并获取总概念是可行的,但我还需要获取另一列(类型)的总概念。

我尝试创建另一个数据透视表以显示源表中type列的总数。

SELECT * FROM (SELECT venue, type_, notional FROM ABC ) PIVOT ( SUM(notional) FOR (venue) IN ('A' as A1 , 'B' as B1) ) PIVOT ( SUM(notional) FOR (type_) IN ('Prime') );

我希望看到一个枢轴,它将显示Prime,A1和B1的总数。

1 个答案:

答案 0 :(得分:0)

我认为您不应该对这个问题使用数据透视,而应该使用简单的聚合函数:

SELECT SUM(CASE WHEN venue = 'A' THEN notional END) AS venueA
     , SUM(CASE WHEN venue = 'B' THEN notional END) AS venueB
     , SUM(CASE WHEN type_ = 'Prime' THEN notional END) AS Prime
  FROM ABC

如果仅是一种类型,则可以执行以下操作:

SELECT * FROM 
   (SELECT venue
         , SUM(CASE WHEN type_ = 'Prime' THEN notional END) over() prime
         , notional 
      FROM ABC ) 
  PIVOT ( SUM(notional) FOR (venue) IN ('A' as A1 , 'B' as B1) )

如果还有一个以上的类型,则必须执行多个PIVOT查询,然后再进行JOIN查询:

SELECT * FROM 
   (SELECT * FROM (SELECT venue, notional FROM ABC ) 
     PIVOT ( SUM(notional) FOR (venue) IN ('A' as A1 , 'B' as B1) )) 
CROSS JOIN 
   (SELECT * FROM (SELECT type_, notional FROM ABC ) 
     PIVOT ( SUM(notional) FOR (type_) IN ('Prime' AS Prime)))