场景:
(* denotes primary key)
**CompanyUnit**(*Unit_id, unit_loc,Year);
**Employees**(Unit_id,Dept_id,no_of_emp); (unit_id and dept_id are foreign keys)
**ref_department**(*dept_id,dept_name,dept_desc);
示例数据:
unit_id unit_loc year
------------------------------------
1 Delhi 2003
2 Mumbai 2004
------------------------------------
dept_id dept_name dept_desc
----------------------------------------
101 ABC ABC-AI
102 ABC ABC-BI
103 ABC ABC-CS
104 XYZ XYZ-Testing
105 XYZ XYZ-Development
----------------------------------------------
unit_id dept_id no_of_emp
----------------------------------------------
1 101 5000
2 102 3000
1 103 4000
1 104 2000
2 105 1000
2 101 3000
----------------------------------------------
Required output: A dynamic view or select:
---------------------------------------------------------------------------
unit_id unit_loc ABC-AI ABC-BI ABC-CS XYZ-Testing XYZ-Development
---------------------------------------------------------------------------
1 Delhi 5000 4000 2000
2 Mumbai 3000 3000 1000
---------------------------------------------------------------------------
问题是ref_department中的每个新部门都对应于view / select查询中的新列。
我写了下面的查询:
variable DEPARTMENTS VARCHAR2(100)
BEGIN
:DEPARTMENTS :=NULL;
FOR cur_rec IN (SELECT DISTINCT DEPT_DESC FROM REF_DEPARTMENT) LOOP
:DEPARTMENTS := :DEPARTMENTS || ''''|| cur_rec.DEPT_DESC|| '''' || ',' ;
END LOOP;
dbms_output.put_line(rtrim(:DEPARTMENTS,','));
select * from
(select uid,uloc,uyear, depdesc, emp from
(select C.unit_id as uid, C.unit_loc as uloc,C.year as uyear, E.DEPT_ID as depid,R.DEPT_NAME as depname,R.DEPT_DESC as depdesc,S.NO_OF_EMP as emp
FROM Unit U INNER JOIN Employees E ON U.Unit_id=E.unit_id INNER JOIN REF_DEPARTMENT R ON E.DEPT_ID=R.DEPT_ID))
pivot
(min(emp) for depdesc in (:departments));
END;
错误:PL / SQL:ORA-56901:不允许使用非常量表达式| unpivot
我在下面提到了链接: Pivoting rows into columns dynamically in Oracle; http://www.orafaq.com/forum/t/187172/
答案 0 :(得分:1)
很久以前(在Oracle的PIVOT查询存在之前),我编写了一个blog post on "Pivot" Queries,它为您提供了一个包的代码,以帮助构建此类查询。
根据您的要求,您可以这样做:
declare
rc sys_refcursor;
begin
rc := pivot.pivot_cursor
( group_cols => 'u.unit_id, u.unit_loc'
, pivot_col => 'rd.dept_desc'
, tables => 'CompanyUnit x, Employees e, ref_departmnent rd'
, value_cols => 'e.no_of_emp'
, agg_types => 'sum'
, where_clause => 'e.dept_id = rd.dept_id and e.unit_id = c.unit_id'
);
end;
/
由于ref游标可以具有可变数量的列,因此您需要使用DBMS_SQL包来解析它,找出列名并运行它。起点是将ref游标转换为DBMS_SQL游标:
n := dbms_sql.to_cursor_number(rc);
您需要参考DBMS_SQL程序包文档示例才能更进一步。