【问题标题】:PIVOT / GROUP BY issue on ORACLEORACLE 上的 PIVOT / GROUP BY 问题
【发布时间】: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 )

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

【问题讨论】:

    标签: sql oracle


    【解决方案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 查询。

    【讨论】:

      猜你喜欢
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-20
      • 1970-01-01
      相关资源
      最近更新 更多