'Two-part conditional sql statement
The statement below is querying a log table and I'm trying to get the max budget depending on the scenario if falls within.
Error message:
Expressions referencing the outer query are not supported outside of WHERE/HAVING clause
SELECT
id, status, budget,
CASE
WHEN (status == 'RUNNING' AND status == 'NOT RUNNING')
THEN (SELECT MAX(budget)
FROM status_table
WHERE status == 'RUNNING')
WHEN (status == 'RUNNING')
THEN (SELECT MAX(budget)
FROM status_table
WHERE status == 'RUNNING')
WHEN (status == 'NOT RUNNING')
THEN (SELECT MAX(budget)
FROM status_table
WHERE status == 'NOT RUNNING')
ELSE MAX(budget)
END AS max_budget
FROM
status_table
GROUP BY
id, status, budget
Solution 1:[1]
Seems to me you want to find the row(s) with the maximum budget
where the status
is either RUNNING or NOT RUNNING.
SELECT id
,status
,budget
FROM status_table
WHERE budget = (
SELECT max(budget)
FROM (
SELECT max(budget)
FROM status_table
WHERE status = 'RUNNING'
UNION
SELECT max(budget)
FROM status_table
WHERE status = 'NOT RUNNING'
)
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Abra |