CASE WHEN之后的GROUP BY

时间:2016-11-16 11:37:55

标签: sql oracle

我正在尝试从连接创建一个表,并根据id汇总一些字段。这部分工作得很好。我还试图添加一个额外的列,并使用case语句我想填充它。

这是脚本

CREATE TABLE TABLE1
AS
  SELECT ID, IDC, SUM(AMOUNT) PRICE, SUM(COST) COST, SUM(AMOUNT-COST) PROFIT,
  CASE PROFIT
    WHEN PROFIT < 1000 THEN 'Low'
    WHEN PROFIT < 5000 THEN 'Medium'
    ELSE 'High'
  END AS PROFITLEVEL  
  FROM
    (SELECT DISTINCT ID, IDC, AMOUNT, COST
    FROM ORDER_ITEMS 
    LEFT JOIN ORDERS 
    ON ID = IDC)
  GROUP BY ID, IDC;

然而,这会返回ORA-00905:缺少关键字错误。

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:5)

您以错误的方式使用CASE;此外,您尝试在定义它的同一级别使用别名PROFIT

您需要修改CASE并使用提供PROFIT而不是别名PROFIT的表达式:

CREATE TABLE TABLE1 AS
      SELECT ID,
             IDC,
             SUM(AMOUNT) PRICE,
             SUM(COST) COST,
             SUM(AMOUNT - COST) PROFIT,
             CASE 
                WHEN SUM(AMOUNT - COST) < 1000 THEN 'Low'
                WHEN SUM(AMOUNT - COST) < 5000 THEN 'Medium'
                ELSE 'High'
             END AS PROFITLEVEL
        FROM (SELECT DISTINCT ID,
                              IDC,
                              AMOUNT,
                              COST
                FROM ORDER_ITEMS LEFT JOIN ORDERS ON ID = IDC)
    GROUP BY ID, IDC;

如果您需要检查单个值,则尝试使用CASE的方式非常有用;例如:

select level,
       case level
         when 1 then 'one'
         when 2 then 'two'
         else 'other'
       end
from dual
connect by level <=3