I tried this query below but it still returns days that had -1 values. I want the where clause to return rows that are 2 days or newer. Thanks!
SELECT uniqueKey,(TO_DAYS(TimeStampColumn) - TO_Days(Now())) as 'dayDiff'
FROM couponextractor.tblresults
where 'dayDiff' >= 0
Because you just compare string 'daydiff' >= 0, which always evaluates to 0 => true
You need to get rid of quotes and use HAVING, beside that's very inefficient query... it's better to compute the date before and just use >= operator on the column.
HAVING dayDiff >= 0
So just compute the exact date, and then just do
WHERE TimeStampColumn >= "XXXX-XX-XX AA:AA:AA" so it can be optimized by the server if you have indexes.
SELECT * FROM tbl WHERE datetime < NOW() - INTERVAL 2 DAY
Why don't you use the MYSQL DATEDIFF- Function?
SELECT uniqueKey,DATEDIFF(TimeStampColumn,Now()) as 'dayDiff'
FROM couponextractor.tblresults
where DATEDIFF(TimeStampColumn,Now()) >= 1
Think this will do the job. Perhaps you have to cast the TimeStampColumn.
Related
Hi i want to substruct to fields between the min and the max date heres my query:
SELECT Max(km) - MIN(km)
from positions
where deviceid = 2
and cast(devicetime as date) between MIN('2017-03-23') and Max('2017-03-23'))
but it gives an error.
PS, devicetime in the database is a datetime type, i'm using mysql
the error is:invalide group function
You do not need MIN and MAX in between:
SELECT Max(km) - MIN(km)
from positions
where deviceid = 2
and cast(devicetime as date) between '2017-03-23 00:00:00' and '2017-03-23 23:59:59'
Try this instead:
SELECT Max(km) - MIN(km)
from positions
where deviceid = 2
and cast(devicetime as date) between '2017-03-23' and '2017-03-23'
You can't use aggregation functions in the where clause, only in select, having or order by clause.
Remove min & max from where....that is not allowed. Try the below sql. Added timestamp so you get the accurate result.
SELECT Max(km) - MIN(km)
from positions
where deviceid = 2
and cast(devicetime as date) between '2017-03-23 00:00:00' and '2017-03-23 23:59:59'
In SQL Server you can use below code,
SELECT Max(km) - MIN(km) KiloMeter FROM positions
where deviceid = 2
Group by deviceid,devicetime
Having cast(devicetime as datetime) between MIN('2017-03-21') and Max('2017-03-26')
Please look in to aggregate and non-aggregate functions..
Thank you..
Your specific problem are the aggregation functions in the WHERE clause. However, you should also note that when using columns in the WHERE, it is a bad idea to use functions or type casting. That prevents the use of indexes.
So, a better version uses inequalities:
select min(km) - max(km)
from positions
where deviceid = 2 and
devicetime >= '2017-03-23' and
devicetime < '2017-03-24';
If performance is an issue, you want an index on positions(deviceid, devicetime, km).
I have the following query which I'm assuming should return results :
SELECT
*
FROM
media
WHERE
sent < package
AND
flag = 0
AND
UNIX_TIMESTAMP(last_run) + 1800 < UNIX_TIMESTAMP(NOW())
ORDER BY
last_run ASC
LIMIT 1
I have the following row inside my DB
`last_run` = '2014-09-13 17:30:0'
`flag` = '0'
`sent` = '4'
`package` = '400'
As now it's currently 2014-09-15 02:53:57 as per the server with a time() of 1410749659 I assume this should be returned? if not, what's the reason behind this?
When checking the timestamps against mySQL I'm getting the following result from this query
SELECT UNIX_TIMESTAMP(last_run), UNIX_TIMESTAMP(NOW()), last_run FROM media LIMIT 1
----------------------------------------------------------------------------
UNIX_TIMESTAMP(last_run) UNIX_TIMESTAMP(NOW()) last_run
1410752462 1410750296 2014-09-14 20:41:02
Q: I assume this [row] should be returned?
A: Yes, we'd expect the row you described to be returned (assuming that there's not implicit data conversions going, e.g. the datatype of the sent and package columns are integer.
With last_run column of datatype DATETIME, we'd expect this predicate:
UNIX_TIMESTAMP(last_run) + 1800 < UNIX_TIMESTAMP(NOW())
would be equivalent to:
last_run < NOW() - INTERVAL 1800 SECOND
The most likely explanation is that there is no row in the table that satisfies all of the predicates; the other predicates should also be investigated. (Test with those other predicates removed.)
Why are you using UNIX_TIMESTAMP. Assuming last_run is datetime, just do:
SELECT m.*
FROM media m
WHERE sent < package AND flag = 0 AND
last_run < now() - interval 30 minute
ORDER BY last_run ASC
LIMIT 1;
I am in the situation where i want to match a date range with another date range, it might be simple but i am stuck at it.
Below is table structure
Table - lifecycles
life_id
life_start_date
life_end_date
then a few records as below
1 - 07/23/2013 - 07/24/2013
2 - 07/15/2013 - 07/25/2015
3 - 03/10/2013 - 03/10/2014
Now i want to search these records by date range and want to see if some life exists in that range; e.g. i want to find the lives between 08/01/2013 - 01/01/2014
As expected result it should select the life#2 and life#3
How can this be done with MySQL query?
Any help is highly appreciated.
This query should do it:
SELECT
*
FROM
lifecycles
WHERE
str_to_date(life_start_date, '%m/%d/%Y') <= '2014-01-01'
AND str_to_date(life_end_date, '%m/%d/%Y') >= '2013-08-01';
Which basically means life hasn't started before the end of the range you are looking for, and life didn't end before the range start.
Since you keep dates in VARCHAR format, you need to use str_to_date function, which is bad since MySQL won't be able to utilize any possible indexes you have on start_date or end_date columns.
This might help you.
SELECT SUM( IF( '2014-01-02' BETWEEN from_date AND to_date, 1, 0 ) ) AS from_exist,
SUM( IF( '2014-02-12' BETWEEN from_date AND to_date, 1, 0 ) ) AS to_exist
FROM date_range
So based on the results you can check whether date is between existing date range or not.
So you want to exclude lifes that are ended BEFORE 08/01/2013 and the ones that are not started AFTER 01/01/2014. This should work:
SELECT *
FROM lifecycles as alive
WHERE NOT EXISTS (
SELECT 1
FROM lifecycles as dead
WHERE dead.life_id = alive.life_id
AND (str_to_date(life_start_date, '%m/%d/%Y') > '2014-01-01'
OR str_to_date(life_end_date, '%m/%d/%Y') < '2013-08-01'))
I'm looking for a simple way to select datetime columns which are 000-00-00 00:00:00 (basically the default unset value).
The following query seems to be working:
SELECT * FROM myTable WHERE datetimeCol < 1
But will this reliably work all the time and across different mysql versions?
I would check for "zero" dates like this:
SELECT * FROM myTable WHERE datetimeCol = CONVERT(0,DATETIME)
I would prefer the equality predicate over an inequality predicate; it seems to convey my intentions more clearly. And if there are more predicates in the statement, and if the datetimeCol is a leading column in an index, it may help the optimizer make use of a multi-column index.
Try this:
SELECT * FROM myTable WHERE datetimeCol = '0000-00-00 00:00:00'
Might seem obvious in hindsight ;)
What about comparing to 0 value:
datetimeCol = 0
Try this:
SELECT * FROM myTable WHERE UNIX_TIMESTAMP(datetimeCol) = 0
Im running a sql query that is returning results between dates I have selected (2012-07-01 - 2012-08-01). I can tell from the values they are wrong though.
Im confused cause its not telling me I have a syntax error but the values returned are wrong.
The dates in my database are stored in the date column in the format YYYY-mm-dd.
SELECT `jockeys`.`JockeyInitials` AS `Initials`, `jockeys`.`JockeySurName` AS Lastname`,
COUNT(`runs`.`JockeysID`) AS 'Rides',
COUNT(CASE
WHEN `runs`.`Finish` = 1 THEN 1
ELSE NULL
END
) AS `Wins`,
SUM(`runs`.`StakeWon`) AS 'Winnings'
FROM runs
INNER JOIN jockeys ON runs.JockeysID = jockeys.JockeysID
INNER JOIN races ON runs.RacesID = races.RacesID
WHERE `races`.`RaceDate` >= STR_TO_DATE('2012,07,01', '%Y,%m,%d')
AND `races`.`RaceDate` <= STR_TO_DATE('2012,08,01', '%Y,%m,%d')
GROUP BY `jockeys`.`JockeySurName`
ORDER BY `Wins` DESC`
It's hard to guess what the problem is from your question.
Are you looking to summarize all the races in July and the races on the first of August? That's a slightly strange date range.
You should try the following kind of date-range selection if you want to be more precise. You MUST use it if your races.RaceDate column is a DATETIME expression.
WHERE `races`.`RaceDate` >= STR_TO_DATE('2012,07,01', '%Y,%m,%d')
AND `races`.`RaceDate` < STR_TO_DATE('2012,08,01', '%Y,%m,%d') + INTERVAL 1 DAY
This will pick up the July races and the races at any time on the first of August.
But, it's possible you're looking for just the July races. In that case you might try:
WHERE `races`.`RaceDate` >= STR_TO_DATE('2012,07,01', '%Y,%m,%d')
AND `races`.`RaceDate` < STR_TO_DATE('2012,07,01', '%Y,%m,%d') + INTERVAL 1 MONTH
That will pick up everything from midnight July 1, inclusive, to midnight August 1 exclusive.
Also, you're not using GROUP BY correctly. When you summarize, every column in your result set must either be a summary (SUM() or COUNT() or some other aggregate function) or mentioned in your GROUP BY clause. Some DBMSs enforce this. MySQL just rolls with it and gives strange results. Try this expression.
GROUP BY `jockeys`.`JockeyInitials`,`jockeys`.`JockeySurName`
My best guess is that the jocky surnames are not unique. Try changing the group by expression to:
group by `jockeys`.`JockeyInitials`, `jockeys`.`JockeySurName`
In general, it is bad practice to include columns in the SELECT clause of an aggregation query that are not included in the GROUP BY line. You can do this in MySQL (but not in other databases), because of a (mis)feature called Hidden Columns.