How to write proper MySQL case statement - mysql

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.

Related

use case when to show column conditional value in MySQL

I would like to add a column and show customer rewards status based on their points.
However, MySQL states there is an error in the syntax which I cannot figure out why.
My code is as below, I got the error msg that SELECT is not valid at this position.
SELECT customer_id, first_name,
CASE points
WHEN > 3000 THEN 'Gold'
WHEN BETWEEN 2000 to 3000 THEN 'Silver'
ELSE 'Bronze'
END AS rewards_status
FROM customers
The short syntax for case, which you are using here (like: case <expr> when <val> then ... end) only supports equality condition; this does not fit your use case, which requires inequality conditions. You need to use the long case syntax (like: case when <condition> then ... end).
Also, there is no need for between in the second condition. Branches of a case expression are evaluated sequentially, and the process stops as soon as a condition is fullfilled, so you can do:
select
customer_id,
first_name
case
when points > 3000 then 'Gold'
when points > 2000 then 'Silver'
else 'Bronze'
end as reward_status
from customers
You may use the alternative syntax for CASE expressions here:
SELECT
customer_id,
first_name,
CASE WHEN points > 3000 THEN 'Gold'
WHEN points BETWEEN 2000 to 3000 THEN 'Silver'
ELSE 'Bronze' END AS rewards_status
FROM customers;

MySQL compare different values in case when function

In this query I use the CASE WHEN function to compare variables values in two different conditions. The problem is the number, because return a value = 1, but the correct result is NULL (20 is > of 8).
SELECT DISTINCT
case
when '20'>= '8' then null
when '20'< '8' then '1'
ELSE '0'
end checkValue
FROM DUAL;
How to resolve this problem?
The query run correctly if change 8 with 08. This solution is not applicable to because from variable arrive numers: 10 100 1000 units.
Thanks
I have change the field type from VARCHAR to DECIMAL and in this case work fine.
if you want compare string remember that string '20' < '8' so 'AB' is < 'C'
SELECT DISTINCT
case
when '20'>= '08' then null
when '20'< '08' then '1'
ELSE '0'
end checkValue
FROM DUAL;
otherwise if you want a number compare then you shoudl convert tne string as number
You need just cast strings to some numeric data type and then compare, for example
SELECT DISTINCT
case
when cast('20' as signed)>= cast('8' as signed) then null
when cast('20' as signed)< cast('8' as signed) then '1'
ELSE '0'
end checkValue
FROM DUAL;
Side note: DISTINCT no makes sense in this particular case

SQL - Time Range (CASE WHEN)

I am working on a Time Query with the following logic. But I am not familiar with time query. Can anyone help?
CASE WHEN (07:00:00) TO (07:10:00) is between [STARTTIME] AND [STOPTIME] THEN 'YES'
Start Time and Stop Time are both DateTime Field
Why not
CASE WHEN '07:00:00' >= [STARTTIME] AND '07:10:00' <= [STOPTIME] THEN 'YES'
if I understand clearly what you want to do.
HERE is the query :- I used #start_Time(for STARTIME) and #end_Time (for STOPTIME) as local variable you can replace them. (As you said between i am taking in between those values if you need to include those time too then instead of > you need to put >= and same with < replace with <=).
select CASE WHEN ((time_to_sec(timediff('07:00:00', time(#Start_Time))))>0
AND (time_to_sec(timediff('07:00:00', time(#end_Time))))<0)
AND
((time_to_sec(timediff('07:10:00', time(#Start_Time))))>0
AND (time_to_sec(timediff('07:10:00', time(#end_Time))))<0) =1
THEN 'YES' else 'NO' END
Hope it helps you !!

DATEDIFF SQL Query

I am at the final stage of my project and have the problem to find if a job is overdue. I link this to priority for example if a job has a priority of 1 it must be complete in 1 day, a priority of 4 then 4 days.
I have come up with a CASE however this doesn't seem to work any help would be appreciated.
SELECT `defect_Id`,`Overtasked`
WHERE
CASE DATEDIFF(DD,`date_Investigaton` - `CURRENT_DATE()`) >= `priority` AS Overtasked
THEN `Overtasked` == 'YES'
ELSE `Overtasked` == 'NO'
END
Solution
`SELECT defect_Id,
CASE WHEN DATEDIFF(date_Investigated, CURDATE()) >= priority
THEN 'YES'
ELSE 'NO'
END AS Overtasked
FROM defect_report
WHERE defect_Id = '82'`
Appreciate the guidance you guys give!
You are completely mixing up SQL dialects and even there are syntax errors.
Assuming you are talking about MS SQL Server let's try this:
SELECT defect_Id,
CASE WHEN DATEDIFF(DD, date_Investigaton, getdate()) >= priority
THEN 'YES'
ELSE 'NO'
END AS Overtasked
FROM <YourTable>
WHERE <YourWhereIfAny>
If date_Investigation is a DATE column, the subtraction date_Investigation - CURRENT_DATE() produces the number of days you need.
Otherwise (if it is a DATETIME, for example) both operands are converted to float and the result is something you are totally not expecting. For such situations use the DATEDIFF() function. It interprets its arguments as DATE (ignores the time part) and returns the integer number of days between the two dates.
Your query should be like:
SELECT
`defect_Id`,
IF (DATEDIFF(`date_Investigaton`, CURRENT_DATE()) >= `priority`, 'YES', 'NO')
AS `Overtasked`
FROM [...your table name here...]
WHERE [...conditions...]
Replace the parts in square brackets ([...]) with the name of the table where to get the data from and some conditions to limit the number of returned rows (otherwise it will get the entire table which, most probably, is not what you want).
Btw, CURRENT_DATE() is also a function. If you write it in backquotes (``), MySQL will try to find a column with this name and it will fail.
Read the accepted answer for this question. It explains when to use back ticks, single quotes or double quotes in MySQL (and partially in PHP).

using mysql datediff with an elseif or case statement

I have the following line of code that can either return one of 2 conditions ('Expired','Active'). I needed to use DATEDIFF to figure out the dates I needed.
However, now I need to alter this code so that I can add a sort of else if condition if neither of the 2 conditions are met and result to 'Unknown'.
I have this so far:
SELECT
IF(DATEDIFF(#endDate:=ADDDATE(h.StartDate,Interval h.NumMonth Month),NOW())<0,'Expired',
IF(DATEDIFF(#endDate,NOW())<120,'Expires in 120 days or less','Active')) AS bActive
FROM ...
So, for now, I have Expired, Active but I also want to include else 'Unknown' to be included as option. How would I alter this logic? Do I need to use ELSEIF or CASE? What should I use?
Use case instead of if. First, case is ANSI standard, so it works across databases. Second, it handles multiple conditions better. I think your logic is:
SELECT (CASE WHEN DATEDIFF(ADDDATE(h.StartDate, Interval h.NumMonth Month), NOW()) < 0
THEN 'Expired'
WHEN DATEDIFF(ADDDATE(h.StartDate, Interval h.NumMonth Month), NOW()) < 120
THEN 'Expires in 120 days or less'
ELSE 'Active'
END) AS bActive