DATEDIFF SQL Query - mysql

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).

Related

I am trying to work with query where I want the count of number of days between two dates to be added up to tottal

RespaApp is a date & ProcessingMilestone is a date. Now I want to know the number of days it took for a file from RespaApp date to ProcesingMilestone date, so I am doing DateIFF sql command but it's not working. Anyone?
case when RespaApp is not null and ProcessingMilestone is not null DATEDIFF(day, RespaApp, ProcessingMilestoneDate) end
I think it's the null cheek which is causing error, as this is being done on a software so there's a separate page to filter for nulls.
In mysql datediff() has only 2 parameters (2 dates), it is the timestampdiff() function that has 3 parameters as you described. Either take the day parameter out or change the function name.
You are also missing the then keyword before the function call:
... then datediff(...) ...
Mysql datediff require only 2 params and return the value in days
select case when (RespaApp is not null and ProcessingMilestone is not null ) THEN
DATEDIFF(RespaApp, ProcessingMilestoneDate) else null end
from your_table

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 !!

SQL query to select values grouped by hour(col) and weekday(row) based on the timestamp

I have searched SO for this question and found slightly similar posts but was unable to adapt to my needs.
I have a database with server requests since forever, each one with a timestamp and i'm trying to come up with a query that allows me to create a heatmatrix chart (CCC HeatGrid).
The sql query result must represent the server load grouped by each hour of each weekday.
Like this: Example table
I just need the SQL query, i know how to create the chart.
Thank you,
Those looks like "counts" of rows.
One of the issues is "sparse" data, we can address that later.
To get the day of the week ('Sunday','Monday',etc.) returned, you can use the DATE_FORMAT function. To get those ordered, we need to include an integer value 0 through 6, or 1 through 7. We can use an ORDER BY clause on that expression to get the rows returned in the order we want.
To get the "hour" across the top, we can use expressions in the SELECT list that conditionally increments the count.
Assuming your timestamp column is named ts, and assuming you want to pull all rows from the year 2014, we start with something like this:
SELECT DAYOFWEEK(t.ts)
, DATE_FORMAT(t.ts,'%W')
FROM mytable t
WHERE t.ts >= '2014-01-01'
AND t.ts < '2015-01-01'
GROUP BY DAYOFWEEK(t.ts)
ORDER BY DAYOFWEEK(t.ts)
(I need to check the MySQL documentation, WEEKDAY and DAYOFWEEK are real similar, but we want the one that returns lowest value for Sunday, and highest value for Saturday... i think we want DAYOFWEEK, easy enough to fix later)
The "trick" now is the columns across the top.
We can extract the "hour" from timestamp using the DATE_FORMAT() function, the HOUR() function, or an EXTRACT() function... take your pick.
The expressions we want are going to return a 1 if the timestamp is in the specified hour, and a zero otherwise. Then, we can use a SUM() aggregate to count up the 1. A boolean expression returns a value of 1 for TRUE and 0 for FALSE.
, SUM( HOUR(t.ts)=0 ) AS `h0`
, SUM( HOUR(t.ts)=1 ) AS `h1`
, SUM( HOUR(t.ts)=2 ) AS `h2`
, '...'
, SUM( HOUR(t.ts)=22 ) AS `h22`
, SUM( HOUR(t.ts)=23 ) AS `h23`
A boolean expression can also evaluate to NULL, but since we have a predicate (i.e. condition in the WHERE clause) that ensures us that ts can't be NULL, that won't be an issue.
The other issue we can encounter (as I mentioned earlier) is "sparse" data. To illustrate that, consider what happens (with our query) if there are no rows that have a ts value for a Monday. What happens is that we don't get a row in the resultset for Monday. If it does happen that a row is "missing" for Monday (or any day of the week), we do know that all of the hourly counts across the "missing" Monday row would all be zero.

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

Inequality sign in SQL case statement seems to work backwards?

n00b questioner here. I'm trying to do a query that checks if the most recent activity is within the last 24 hours. I technically can get the result I want, but the inequality in my case statement has to be in the opposite direction as would make sense to me. Here's my query:
SELECT sqs.registration_id,
MAX(sqs.completed_at) AS 'most recent activity',
DATE_SUB(NOW(), INTERVAL 1 DAY) AS 'one day ago',
'recent activity?' = CASE
WHEN MAX(sqs.completed_at) <
DATE_SUB(NOW(), INTERVAL 1 DAY)
THEN 1
ELSE 0
END
FROM student_quiz_states sqs
WHERE sqs.score = 100
GROUP BY sqs.registration_id
Here's an example result:
XXXXX 2011-08-02 16:23:53 2011-12-05 00:06:05 0
This user did not have activity in the last 24 hours, so the last value returns 0, as I want it to.
However, that doesn't make any sense to me. Shouldn't the case statement return a 1, since the first datetime is much earlier than one day ago? It would make sense to me if my desired results were returned when my when_clause contained a > instead of a <.
Any explanations would be appreciated.
The problem is that your query contains 'recent activity?' = CASE ... END where it should have CASE ... END AS 'recent activity?'. The former is an equality-test rather than an expression with an alias. The reason for the seemingly "inverted" behavior is that, since the CASE expression is numeric (it evaluates to 0 or 1), MySQL performs a numeric equality-test, by converting 'recent activity?' to 0.0 (detailed rules here), such that 'recent activity?' = CASE ... END is true when the CASE expression gives 0 and false when it gives 1. Since MySQL represents true as 1 and false as 0, the end result is the opposite of what you were expecting.
(Note: An earlier version of this answer, while making the same basic point about equality-tests vs. aliases, and about false and true being 0 and 1, was vague/confused in other respects, since I didn't recognize that the DBMS was MySQL, and was not aware that some DBMSes allow single-quotes to be used when quoting aliases. So if some of the comments above and below seem a bit strange, it's because they're referring to that version. The current state of the answer is thanks in large part to those comments.)