【问题标题】:Changing Row into Columns将行更改为列
【发布时间】:2012-11-05 12:00:42
【问题描述】:

我目前正在从我的查询中得到这个输出:-

Count(Total)| Type1
-----------------
 24            T1

  22           T2

但我想要这样的输出:-

 T1   T2
----------
 24   22

请注意,Type1 列可以包含任何值,例如 T1、T2、T3,因此我无法修复查询中的值。我用的是Oracle 10g,怎么办?

【问题讨论】:

    标签: c# oracle oracle10g pivot dynamic-sql


    【解决方案1】:

    Oracle 10g 没有PIVOT 函数,因此您可以使用带有CASE 的聚合:

    select 
      sum(case when type1 = 'T1' then total end) T1,
      sum(case when type1 = 'T2' then total end) T2
    from <yourquery goes here>
    

    SQL Fiddle with Demo

    或者您可以将其直接实现到与此类似的查询中,使用 SUM() 聚合将计算与 CASE 语句中的 type1 值匹配的每次出现:

    select 
      sum(case when type1 = 'T1' then 1 else 0 end) T1,
      sum(case when type1 = 'T2' then 1 else 0 end) T2
    from yourtable
    

    如果您有未知数量的值要转换为列,那么您将需要使用类似于以下的过程:

    CREATE OR REPLACE procedure dynamic_pivot(p_cursor in out sys_refcursor)
    as
        sql_query varchar2(1000) := 'select ';
    
        begin
            for x in (select distinct type1 from yourtable order by 1)
            loop
                sql_query := sql_query ||
                  ' , sum(case when type1 = '''||x.type1||''' then 1 else 0 end) as '||x.type1;
    
                    dbms_output.put_line(sql_query);
            end loop;
    
            sql_query := sql_query || ' from yourtable';
    
            open p_cursor for sql_query;
        end;
    /
    

    然后执行它:

    variable x refcursor
    exec dynamic_pivot(:x)
    print x
    

    【讨论】:

    • Type1 列可以包含任何值,如 T1、T2、T3...我无法在查询中修复它
    • @Devesh 请查看我的编辑,我添加了动态版本的示例
    • @Devesh 如果对此还有其他问题,那么您应该发布一个新问题。发布新问题时,请解释您遇到的任何错误。
    • 我需要一个查询帮助。我已经在这个论坛发帖stackoverflow.com/questions/13410464/oracle-10g-query-format
    猜你喜欢
    • 1970-01-01
    • 2019-01-14
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多