2012-02-17 133 views
2

我的第一个查询在那里我得到了问题就在这里:Tricky GROUP BY issue on ORACLE现在肯定解决。PIVOT/GROUP BY问题上ORACLE

但是我有一个新问题。我尝试转换它,再一次有这个输出:

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

这里的数据可以帮助您构建这样的输出。我尝试再次使用René在解决的问题中给出的查询来使用unpivot/pivot,但不幸的是我得到了错误: “ORA-56901:非常量表达式不允许用于pivot | unpivot值”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 
) 

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

回答

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) 
); 
+0

非常感谢您!它的工作原理,(顺便说一句,只有一个错字与特征词) 我开始更好地理解这个PIVOT/UNPIVOT功能;) – Ajantis 2012-02-20 08:56:49

0

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

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