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
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.
The GROUP BY clause follows the WHERE clause and comes before the ORDER BY clause.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With