简体   繁体   中英

How to write proper MySQL case statement

I've typed out the query below and I get a syntax error after the first when of the the CASE part. Please help correct.

SELECT state.name, country.name, AVG(state_weather_stats.humidity) AS average_monthly_humidity,
CASE AVG(state_weather_stats.temperature)
    WHEN >=0 AND < 15 THEN “COLD”
    WHEN >= 15 AND <30 THEN “WARM”
    ELSE “HOT”
END AS weather_type

If you're using inequalities, you can't use the CASE <expr> WHEN... syntax. That syntax is only usable when you're doing equality comparisons.

So you can use the CASE WHEN <expr>... syntax instead:

SELECT state.name, country.name, AVG(state_weather_stats.humidity) AS average_monthly_humidity,
CASE 
    WHEN average_monthly_humidity >= average_monthly_humidity THEN 'COLD'
    WHEN average_monthly_humidity >= 15 AND average_monthly_humidity <30 THEN ...something...
    ELSE 'HOT'
END AS weather_type

I don't know what you want where I put "...something..." but you do need a THEN clause before the ELSE.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM