Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GROUP BY after CASE WHEN

Tags:

sql

oracle

I am trying to create a table from a join and summing some fields based on id. This part is working great. I am also trying to add an additional column and using a case when statement I want to populate it.

Here is the script

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;

This however returns a ORA-00905 : Missing keyword error.

Any help would be appreciated

like image 297
Akaitenshi Avatar asked Nov 16 '16 11:11

Akaitenshi


People also ask

Can we use case when in GROUP BY?

The case statement in SQL returns a value on a specified condition. We can use a Case statement in select queries along with Where, Order By, and Group By clause. It can be used in the Insert statement as well.

WHERE comes after or before GROUP BY?

The GROUP BY clause follows the WHERE clause and comes before the ORDER BY clause.

Can we use GROUP BY with case in SQL?

type , CASE WHEN attempt. Or provide a column alias that's different from any column name in the FROM list - or else that column takes precedence: SELECT ... , CASE WHEN attempt. result = 0 THEN 0 ELSE 1 END AS result1 ... GROUP BY model.name, attempt.

Does GROUP BY come after ORDER BY?

Using Group By and Order By Together When combining the Group By and Order By clauses, it is important to bear in mind that, in terms of placement within a SELECT statement: The GROUP BY clause is placed after the WHERE clause. The GROUP BY clause is placed before the ORDER BY clause.


1 Answers

You are using the CASE in a wrong way; besides, you try to use the alias PROFIT at the same level you define it.

You need to edit you CASE and use the expression that gives the PROFIT instead of the alias 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;

The way you tried to use the CASE is useful if you need to check single values; for example:

select level,
       case level
         when 1 then 'one'
         when 2 then 'two'
         else 'other'
       end
from dual
connect by level <=3
like image 194
Aleksej Avatar answered Sep 29 '22 06:09

Aleksej