Oracle中的动态跨选项卡查询

时间:2012-09-04 07:21:44

标签: sql oracle dynamic pivot

我需要创建一个动态的交叉表查询,其中列并不总是固定在数字中,所以不能使用大小写时的硬代码。我用谷歌搜索,它确实找到了一个关于在SQL Server中做同样事情的博客,但我想知道是否有任何这样的文章博客在甲骨文做同样的事情。没有在SQL Server中工作。 Fol是关于我的问题的信息。

我编写的硬编码交叉表查询

SELECT

LU_CITY.CITY_NAME as "City",
count(CASE WHEN emp.emp_category='Admin'  THEN emp.emp_id END) As "Admins",
count(CASE WHEN emp.emp_category='Executive'  THEN emp.emp_id END) As "Executive",
count(CASE WHEN emp.emp_category='Staff'  THEN emp.emp_id END) As "Staff",
count(emp.emp_id) As "Total"

FROM emp, LU_CITY

where

   LU_CITY.CITY_ID = EMP.CITY_ID(+)
group by
LU_CITY.CITY_NAME, LU_CITY.CITY_ID
order by
LU_CITY.CITY_ID

        emp (emp_id, emp_name, city_id, emp_category)
        lu_city(city_id,city_name)

查询结果

          ------------------------------------------
          City | Admins | Executive | Staff . . . .
          ------------------------------------------ 
          A    |    1   |   2       | 3
          B    |    0   |   0       | 4
          .    |    .   |   .       | . 
          .
          .

用户可以根据需要添加emp_category。查询应该是应该动态生成所有这些类别。

高度赞赏这方面的任何指导。

先谢谢

1 个答案:

答案 0 :(得分:2)

您可以使用动态游标执行从VARCHAR2变量编译的动态SQL:

DECLARE 
       w_sql             VARCHAR2 (4000);
       cursor_           INTEGER;
       v_f1    NUMBER (6);
       v_f2    NUMBER (2);
       v_some_value_2_filter_4    NUMBER (2);
       rc      INTEGER         DEFAULT 0;
BEGIN
        -- join as many tables as you need and construct your where clause
        w_sql :='SELECT f1, f2 from TABLE1 t1, TABLE2 t2, ... WHERE t1.f1 =' || v_some_value_2_filter_4 ; 

       -- Open your cursor
       cursor_ := DBMS_SQL.open_cursor;
       DBMS_SQL.parse (cursor_, w_sql, 1);
       DBMS_SQL.define_column (cursor_, 1, v_f1);
       DBMS_SQL.define_column (cursor_, 2, v_f2);
      -- execute your SQL
       rc := DBMS_SQL.EXECUTE (cursor_);

       WHILE DBMS_SQL.fetch_rows (cursor_) > 0
       LOOP
          -- get values from record columns
          DBMS_SQL.COLUMN_VALUE (cursor_, 1, v_f1);
          DBMS_SQL.COLUMN_VALUE (cursor_, 2, v_f2);

          -- do what you need with v_f1 and v_f2 variables

       END LOOP;

END;

或者您可以使用execute immediate,如果您只需要检查值或执行并插入/更新/删除查询,则更容易实现

    w_sql :='select f1 from table where f1 = :variable';
    execute immediate w_sql into v_f1 using 'valor1'

这里有关于动态游标的更多信息: http://docs.oracle.com/cd/B10500_01/appdev.920/a96590/adg09dyn.htm