我尝试在Oracle APEX 5中构建PIVOT表。我有3个表:
表CAB
身份证号码
CAB_DATE DATE
表CAB_DEP_TO_CAB
CAB_ID VARCHAR2
DEP_ID VARCHAR2
表CAB_DEP
身份证号码
DEP_NAME VARCHAR2
我尝试过:
SELECT DISTINCT
LISTAGG('''' || CAB_DATE || ''' AS ' || CAB_DATE,',')
WITHIN GROUP (ORDER BY CAB_DATE) AS temp_in_statement
FROM (SELECT DISTINCT CAB_DATE FROM CAB);
这没问题,但PIVOT没问题
SELECT * FROM
(SELECT cd.dep_name, c.cab_date, d.dep_id FROM cab c INNER JOIN cab_dep_to_cab d ON c.id = d.cab_id INNER JOIN cab_dep cd ON d.dep_id like ('%' || cd.id || '%') )
PIVOT (SUM(dep_id) FOR c.cab_date IN (&str_in_statement));
它返回错误:ORA-01748“此处仅允许使用简单的列名”
有人可以看到我的错误吗? :O
顺便说一句。我试图从此处使用代码:Dynamic pivot in oracle sql
答案 0 :(得分:1)
我认为这里的问题是,您在数据透视功能中使用的是“ c.cab_date”而不是“ cab_date”。这应该可以工作(不确定为什么在第二个联接上有如此奇怪的联接条件,我用一个更合理的联接条件代替了它):
SELECT * FROM
(SELECT cd.dep_name
, c.cab_date
, d.dep_id
FROM cab c
INNER JOIN cab_dep_to_cab d ON c.id = d.cab_id
INNER JOIN cab_dep cd ON d.dep_id = cd.id
)
PIVOT (SUM(dep_id) FOR cab_date IN (&str_in_statement));
如果我可以为您的表设计添加一些小提示:我建议将“部门ID”之类的列命名为始终相同,这将使代码更具可读性,但这只是出于个人喜好。当然;)
我用这种方式命名事物:
Table CAB
CAB_ID number
CAB_DATE date
Table DEPARTMENTS
DEPARTMENT_ID number
DEPARTMENT_NAME varchar2
Table DEPARTMENT_CABS
CAB_ID number -- not varchar as in your example!
DEPARTMENT_ID number -- not varchar as in your example!