1

我需要创建一个动态交叉表查询,其中列的数量并不总是固定的,因此不能使用 case when 进行硬编码。我用谷歌搜索,它确实找到了一个关于在 SQL Server 中做同样事情的博客,但我想知道是否有任何这样的文章博客关于在 Oracle 中做同样的事情。没有在 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 可以由用户根据需要添加。查询应该是这样的,它应该动态生成所有这些类别。

在这方面的任何指导将不胜感激。

提前致谢

4

1 回答 1

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

于 2012-09-04T07:37:42.640 回答