ORACLE上的PIVOT / GROUP BY问题

时间:2012-02-17 14:42:38

标签: sql oracle

我在这里遇到问题的第一个问题是:Tricky GROUP BY issue on ORACLE现在已经解决了。

但是我有一个新问题。我试着改变它,再一次得到这个输出:

                        |           EMAIL          |              WIFI          | ...         
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        Yes             |             20           |                24          | ...                 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
         No             |              4           |                 0          | ...        
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Unknown             |              1           |                 1          | ...
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

这里的数据可以帮助您构建此类输出。我尝试再次使用unpivot / pivot与René在我引用的已解决问题中给我的查询,但不幸的是我得到了错误 “ORA-56901:不允许非常数表达式的枢轴|非透视值”sighh ......

with 
count_table as (
     select 1001 device_id,  4 quantity from dual union all
     select 1002 device_id, 20 quantity from dual union all
     select 1003 device_id,  1 quantity from dual 
),
device_table as (
     select 1001 id, 'Yes'     wifi, 'No'       email, 'No'  bluetooth from dual union all
     select 1002 id, 'Yes'     wifi, 'Yes'      email, 'No'  bluetooth from dual union all
     select 1003 id, 'Unknown' wifi, 'Unknown'  email, 'Yes' bluetooth from dual 
)

也许这有一个更简单的解决方案?我肯定需要阅读一本关于关系数据库的书:)

2 个答案:

答案 0 :(得分:1)

在推荐您之前的帖子后看起来很简单.. 请尝试以下查询...

with 
count_table as (
     select 1001 device_id,  4 quantity from dual union all
     select 1002 device_id, 20 quantity from dual union all
     select 1003 device_id,  1 quantity from dual 
),
device_table as (
     select 1001 id, 'Yes'     wifi, 'No'       email, 'No'  bluetooth from dual union all
     select 1002 id, 'Yes'     wifi, 'Yes'      email, 'No'  bluetooth from dual union all
     select 1003 id, 'Unknown' wifi, 'Unknown'  email, 'Yes' bluetooth from dual 
)
----------------------------------------
select * from (
      select
        feature,
        yes_no_unknown,
        sum(quantity)  quantity
      from 
         count_table  c join 
         device_table d on c.device_id = d.id
      unpivot  ( yes_no_unknown
                 for feature in (wifi, email, bluetooth)
      ) 
      group by 
      feature,
      yes_no_unknown
)  
pivot ( sum (quantity)
        -- only this line I have changed  ..
        for feature in ('WIFI' as Wifi, 'EMAIL' as Email, 'BLUETOOTH' as Bluetooth)
);

答案 1 :(得分:0)

如果输出表的列数是灵活的,您可以使用一些程序解决方案; PL / SQL或Java。

在PL / SQL中,您可以创建一个二维集合并填充它然后将其打印出来。您可以使用dbms_sql包创建/生成动态SQL查询。