Oracle - 在单个Select语句中编写此查询的任何方法?

时间:2011-11-07 19:35:07

标签: sql oracle oracle11g pivot

我有以下查询:

SELECT * FROM (
    SELECT * FROM View_ExecutiveForecastReport
    WHERE WORKGROUPID IN (94)
)
PIVOT  (SUM(COURSELENGTH) AS LENGTH FOR (WORKGROUPID) IN (
94 as "B2B",
66 as "CFS",
69 as "800IB",
76 as "TSData",
99 as "RetailSales",
103 as "Telesales"
))

我想用单个SELECT而不是嵌套来编写它。我试过了:

SELECT * FROM View_ExecutiveForecastReport
WHERE WORKGROUPID IN (94)
PIVOT  (SUM(COURSELENGTH) AS LENGTH FOR (WORKGROUPID) IN (
94 as "B2B",
66 as "CFS",
69 as "800IB",
76 as "TSData",
99 as "RetailSales",
103 as "Telesales"
))

但我收到错误: ORA-00933:SQL命令未正确结束

我也试过了:

SELECT * FROM View_ExecutiveForecastReport
PIVOT  (SUM(COURSELENGTH) AS LENGTH FOR (WORKGROUPID) IN (
94 as "B2B",
66 as "CFS",
69 as "800IB",
76 as "TSData",
99 as "RetailSales",
103 as "Telesales"
))
WHERE WORKGROUPID IN (94)

这给了我错误: ORA-00904:“WORKGROUPID”:标识符无效

如果我删除WHERE子句,查询工作正常。我也对使用CTE的解决方案持开放态度。

2 个答案:

答案 0 :(得分:1)

这不起作用,因为PIVOT是FROM子句table_reference的table_reference部分的一部分,这就是为什么这样做的原因:

SELECT * FROM View_ExecutiveForecastReport
PIVOT  (SUM(COURSELENGTH) AS LENGTH FOR (WORKGROUPID) IN (
94 as "B2B",
66 as "CFS",
69 as "800IB",
76 as "TSData",
99 as "RetailSales",
103 as "Telesales"
))

由于workgroupid不是作为PIVOT转换中的列返回的,因此不能在WHERE子句中使用它。 SELECT * FROM(子查询)PIVOT的使用很常见,所以我建议你使用它。

答案 1 :(得分:1)

我已经决定发布工作查询的CTE版本,但我不知道这是否比我原来的工作查询提供了任何优势。

WITH V AS (SELECT * FROM View_ExecutiveForecastReport WHERE WORKGROUPID IN (94))
    SELECT * FROM V
    PIVOT  (SUM(COURSELENGTH) AS LENGTH FOR (WORKGROUPID) IN (
    94 as "B2B",
    66 as "CFS",
    69 as "800IB",
    76 as "TSData",
    99 as "RetailSales",
    103 as "Telesales"
    ))