我尝试在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
我认为这里的问题是你在pivot函数中使用“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!