ORACLE 上的 PIVOT / GROUP BY 问题

Posted

技术标签:

【中文标题】ORACLE 上的 PIVOT / GROUP BY 问题【英文标题】:PIVOT / GROUP BY issue on ORACLE 【发布时间】:2012-03-08 23:13:58 【问题描述】:

我在这里遇到问题的第一个查询:Tricky GROUP BY issue on ORACLE 现在肯定已解决。

但是我有一个新问题。我尝试对其进行改造,再一次得到这个输出:

|电子邮件 |无线网络 | ... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 是 | 20 | 24 | ... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 没有 | 4 | 0 | ... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 未知 | 1 | 1 | ... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

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

和 计数表为 ( select 1001 device_id, 4 个数量 from dual union all select 1002 device_id, 20 个数量 from dual union all select 1003 device_id, 1 个数量 from dual ), device_table 为 ( 选择 1001 id, 'Yes' wifi, 'No' email, 'No' bluetooth from dual union all 选择 1002 id, 'Yes' wifi, 'Yes' email, 'No' bluetooth from dual union all 选择 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)
);

【讨论】:

非常感谢!它有效,(顺便说一句,特征词只是一个错字)我开始更好地理解这个 PIVOT / UNPIVOT 功能;)【参考方案2】:

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

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

【讨论】:

以上是关于ORACLE 上的 PIVOT / GROUP BY 问题的主要内容,如果未能解决你的问题,请参考以下文章

Oracle SQL group by 查询,一种 PIVOT [重复]

Python Pandas Group by Count Pivot of multiple columns

使用 PIVOT 函数的行到列 (Oracle)

SQL PIVOT 可以做这样的转换吗?

MySql Group by 与 Pivot

SQL Server Pivot 隐藏group