Stupid420
Stupid420

Reputation: 1419

How to use case properly in SQL

I am getting a minor error with the following SQL code the reason of which I don't understand.

I am using AWS Athena.

SELECT 
    icustay_id, 
    itemid, 
    date_diff('second', TIMESTAMP '1970-01-01 00:00:00', starttime) AS starttime, 
    date_diff('second', TIMESTAMP '1970-01-01 00:00:00', endtime) AS endtime,
    CASE WHEN itemid IN (30120,221906,30047) AND rateuom='mcg/kg/min' THEN CAST(rate AS DECIMAL(10,3))
FROM mimiciii.inputevents_mv
WHERE itemid IN (30128,30120,30051,221749,221906,30119,30047,30127,221289,222315,221662,30043,30307) 
ORDER BY icustay_id, itemid, starttime

Following is the error.

An error occurred (InvalidRequestException) when calling the StartQueryExecution operation: line 2:1: extraneous input 'case' expecting {, ',', 'FROM', 'WHERE', 'GROUP', 'ORDER', 'HAVING', 'LIMIT', 'UNION', 'EXCEPT', 'INTERSECT'} unable to rollback

Upvotes: 0

Views: 166

Answers (1)

Arun Palanisamy
Arun Palanisamy

Reputation: 5459

The syntax for Case expression is :

CASE
WHEN boolean condition THEN result
[WHEN ...]
[ELSE result]
END

You are missing END in your select statement. just add END keyword after your then condition as in below query. It should work fine.

query_vaso_mv = """
select icustay_id, itemid, date_diff('second', timestamp '1970-01-01 00:00:00', starttime) as starttime, date_diff('second', timestamp '1970-01-01 00:00:00', endtime) as endtime,
case when itemid in (30120,221906,30047) and rateuom='mcg/kg/min' then cast(rate as DECIMAL(10,3)) end 
from mimiciii.inputevents_mv
where itemid in (30128,30120,30051,221749,221906,30119,30047,30127,221289,222315,221662,30043,30307) 
order by icustay_id, itemid, starttime
"""

Upvotes: 1

Related Questions