SQL query to select apps used at least once during 3 different days in the last 7 days - mysql

I have a table that contains 2 columns : 1 column "app_id" and 1 column "time".
I am trying to make a SQL request to know the number of "app_id" that have been used at least once in 3 different days, in the last 7 days.
Currently, I achieved selecting all the data in the last 7 days using :
SELECT app_id,time FROM connexions WHERE time BETWEEN NOW() - INTERVAL 167 HOUR AND NOW()
I am using 167 HOUR instead of 7 DAY because I have a 1 hour time difference between my server and the database (no worries about that, i'll fix it later!)
Thanks!

SELECT app_id
FROM connexions
WHERE time BETWEEN NOW() - INTERVAL 167 HOUR AND NOW()
GROUP BY app_id
HAVING COUNT( DISTINCT day(time) ) > 3
Be aware this only works because is a week. If you want something like 3 months you would need be more specific.

Related

MySQL DATE_ADD() not working

In my database I have a table containing some business offers. One of the columns is expire, which contains the date a certain offer expires.
I want to select all offers which expire in 10 days. Here is my code:
SELECT * FROM offers WHERE TIME_ADD(NOW(), INTERVAL 10 DAYS) = expire;
I want to select all columns from offers, where the expiry date is equal date now plus 10 days (so they expire in 10 days). MySQL doesn't let me do that, it marks "=expire" as an error
Syntax error unexpected 'expire' (expire).
Why is that? ( I'm working on MySQL workbench btw)
If you want to find all offers that expire in 10 days, but you're not concerned as to what time in 10 days that they expire, then you can use the following:
SELECT *
FROM offers
WHERE DATE(expire) = DATE_ADD(CURRENT_DATE(), INTERVAL 10 DAYS);
If however you want to find all offers that expire in 10 days, to the exact second, then you can use the following instead:
SELECT *
FROM offers
WHERE expire = DATE_ADD(NOW(), INTERVAL 10 DAYS);
Notice how the first query uses CURRENT_DATE(), which will return only a date value - 2018-08-03. Whereas the second query uses NOW(), which will return a datetime value - 2018-08-03 08:29:00.
replace INTERVAL 10 DAYS with INTERVAL 10 DAY

SQL query to retrieve latest 2 week records

I have a database with CreatedDate is store in Unix epoch time and some other info. I want a query to able to retrieve latest 2 week record base on the last record.
Below is part of the example
ID User Ranking CreatedDate
-------------------------------------------------------
1 B.Sisko 1 1461136714
2 B.Sisko 2 1461123378
3 B.Sisko 3 1461123378
4 B.Sisko 3 1461600137
5 K.Janeway 4 1461602181
6 K.Janeway 4 1461603096
7 J.Picard 4 1461603096
The last record CreatedDate is 25 Apr 2016, so I want the record from 12 Apr to 25 Apr.
I not sure how to compare to get latest data? any suggestion
The simplest method is probably to just subtract two weeks from today's date/time:
where CreatedDate >= UNIX_TIMESTAMP() - 7*24*60*60
Another approach is to convert the value to a date/time:
where from_unixtime(CreatedDate) >= date_sub(now(), interval 2 week)
The advantage of this approach is that it is easier to align to days. So, if you want two weeks starting at midnight:
where from_unixtime(CreatedDate) >= date_sub(curdate(), interval 2 week)
The disadvantage is that the function on the column prevents the use of indices on that column.
EDIT:
This is definitely not how your question was phrased. But in that case, you should use:
select t.*
from t cross join
(select from_unixtime(max(CreatedDate)) as maxcd from t) m
where from_unixtime(CreatedDate) >= date_sub(maxcd, interval 2 week);
It may seem odd, but you need to execute two queries one to find the Maximum Date and knock off 14 days -- and then use that as a condition to requery the table. I used ID_NUM since ID is a reserved word in Oracle and likely other RDBMS as well.
SELECT ID_NUM, USER, RANKING,
TO_DATE('19700101000000', 'YYYYMMDDHH24MISS')+((CreatedDate-18000)
/(60*60*24)) GOOD_DATE
FROM MY_TABLE
WHERE
GOOD_DATE >=
(SELECT MAX( TO_DATE('19700101000000', 'YYYYMMDDHH24MISS')+
((CreatedDate-18000) /(60*60*24))) -14
FROM MY_TABLE)

Logic for dates in sql query for mysql

Hi i am totally confused with a date logic in my mysql query for a cron job to be run everyday at 12:00 AM
I am working on a auto listing website where the car listings are having a expiry date in mysql datetime format.
All the expired listings will be deleted from the website after 7 days from the datetime of the expiry
When the cron job will run it has do following things
Task 1 - Send an email alert to the users telling them that their listing has expired.
So I need to select all those listings which have expired since last time the cron job has been run and not include listings before that in order to send the expiry alert email only once per listing.
I tried following sql query for this task (Again confused with this as well)
SELECT car_id FROM cars WHERE expiry_date > DATE_SUB(NOW(), INTERVAL 1 DAY) AND expiry_date < NOW()
Task 2 - Will send an email alert to users telling them that listing is going to be permanently deleted after 24 hours.
So I need to select all those listings which are going to be deleted in more than 24 hours / 6 days have passed since they were expired and i need to make sure that they get minimum 24 hours time to renew them. Also i need to select / build the sql query in such a way that only those listings get selected which are going to expiry in 1 days and not other in order to avoid multiple email alerts instead of one time email alert
I tried following sql query for this task (I am totally confused with this query)
SELECT car_id FROM cars WHERE expiry_date > DATE_SUB(NOW(), INTERVAL 7 DAY) AND expiry_date < DATE_SUB(NOW(), INTERVAL 1 DAY)
Task 3 - Delete all the listings which were expired more than 7 days ago
I tried following sql query for this task
SELECT car_id FROM cars WHERE expiry_date < DATE_SUB(NOW(), INTERVAL 7 DAY)
Please help me in perfecting all the 3 queries so that the cron does it job exactly as i want. Also please let me where it has to >= (greater than or equal to) or <= (less than or equal to)
Here is the sqlfiddle table structure and couple of records (though they are not expired yet)
http://sqlfiddle.com/#!2/cfcdf
I will really appreciate the help.
Is this what you are looking for? Please try to add another column to see the differnce between expiry_date and current date time for you to get a better idea of the dates you are dealing with. Please look into some dates functions in MYSQL.
SQLFIDDLE DEMO
-- 3rd query expiry dates older than 7 days from
-- today
SELECT car_id, expiry_Date,
DATE_sub(NOW(), INTERVAL 7 DAY)
FROM cars
WHERE expiry_date <=
DATE_sub(NOW(), INTERVAL 7 DAY)
;
-- same
SELECT car_id, expiry_Date,
DATE_ADD(NOW(), INTERVAL -7 DAY)
FROM cars
WHERE expiry_date <=
DATE_ADD(NOW(), INTERVAL -7 DAY)
;
-- 2nd query going to expire in exactly 1 day
SELECT car_id, expiry_date,
Now() + interval 1 day
FROM cars
WHERE expiry_Date = Now() + interval 1 day
;
-- 1st query: expired
SELECT car_id FROM cars
WHERE expiry_date < Now()
;
-- 1st query: expired last 24 hours
SELECT car_id,DATEDIFF(expiry_date, Now())
FROM cars
WHERE expiry_Date < Now()
AND expiry_Date >= Now() - interval 1 day
;
Check out these queries
select * from cars where datediff(EXPIRY_DATE,now())=-1;
select * from cars where
datediff(DATE_ADD(EXPIRY_DATE, interval 24 hour),now())>=1 and
datediff(DATE_ADD(EXPIRY_DATE, interval 24 hour),now()) <=2;
select * from cars where datediff(expiry_date,now())<=-7;
ope they are working according to your need.
fiddle http://sqlfiddle.com/#!2/785ea/5
There is nothing significantly wrong with your queries, if you do not understand the functions that you have used then google them and read about them until you do.
There is a fundamental problem in your approach in that it relies on the cron job being run at exactly 24 hour intevals - to the milisecond - or there will be double ups and/or omissions.
You need another table to store details of when your batch program last ran; intitialise this with 1 row with a date a long time in the past so that we have a starting point.
You can get the most recent batch by SELECT MAX(date_ran) FROM BatchRecordTables. Store this in a local variable T0. Get the current time, store this in a local variable T1 (Do not use NOW() in multiple queries as they will be slightly differant times and you need them to be the same). I do not know the syntax for this is MySQL - you will have to look it up.
Your situations then become.
Send email to people whose listings have expired since that last time the cron job was run i.e. SELECT car_id FROM cars WHERE Expiry_Date BETWEEN T0 AND T1. This will only select people whoose listings have expired between this batch and the previous one.
For the second case, we need to know that these people have got the first email i.e. that their listing had expired before the last batch run so SELECT car_id FROM cars WHERE Expiry_Date BETWEEN DATE_SUB(T1, INTERVAL 6 DAY) AND T0. This will only select people whoose listings expired before the last batch (i.e. they got the exprired email) and more than 6 days ago.
Same logi applies - we want to know they got the second email. SELECT car_id FROM cars WHERE Expiry_Date BETWEEN DATE_SUB(T1, INTERVAL 7 DAY) AND DATE_SUB(T0, INTERVAL 6 DAY)
May I also suggest that you do not permenantly delete the listings but either copy them to a DeletedListings table or Flag them with a Deleted column - each has its own pros and cons. In the information age, never throw data away - you never know when it might be valuable.

How to select/count all records which happened in the last 2 hours? - MYSQL

In MYSQL i have DATE and TIME seperated. I need to count how many times one ip failed to login in the last 2 hours. If he failed too many times, then he can't login for the next 2 hours.
I just don't know which statement is the correct one (maybe none of the 2 below).
SELECT COUNT(`ip`) AS count_failed_logins FROM `failed_logins` WHERE `time`=TIME(CURTIME()+Interval 2 hour)
or
SELECT COUNT(`ip`) AS count_failed_logins FROM `failed_logins` WHERE `time`=TIMEDIFF(CURTIME()+Interval 2 hour)
You can simply do :
SELECT COUNT(`ip`) FROM `failed_logins` WHERE `time` > DATE_SUB(NOW(), INTERVAL 2 HOUR);

MYSQL Select/Group By: How do I remove a group from the result based on a value of one of it's members?

Consider the table of events below. The OrderID field is a foreign key to an Orders table.
OrderID EventType TimeAdded* Processed
1 ... 3 Hours Ago 0
2 ... 5 Minutes Ago 0
1 ... 2 Hours Ago 0
1 ... 1 Hour Ago 0
3 ... 12 Minutes ago 1
3 ... 3 Hours Ago 0
2 ... 2 Hours Ago 0
*TimeAdded is actual a mysql date-time field. I used human readable times here to make the question easier to read.
I need to get a result set that has each OrderID, only once, but only if ALL records attached to a given order ID, that have a proceeded status of 0, have been added more than 15 minutes ago.
In this example, order #2 should be OMITTED from the result set because it has an unprocessed event added within the last 15 minutes. The fact that it has an unprocessed event from 2 hours ago is inconsequential.
Order #3 SHOULD be included. Even though one of its entries was added 12 minutes ago, that entry has already been processed, and should not be considered. Only the "3 hours ago" entry should be considered in this set, and it is greater than 15 minutes ago.
Order #1 SHOULD be included, since all three unprocessed events attached to it occurred more than 15 minutes ago.
I'm not sure if this needs to use a sub-query or group by or possibly both?
pseudo code:
SELECT * FROM OrderEvents WHERE Processed=0 GROUP BY OrderID
OMIT WHOLE GROUP IF GROUP_MIN(TimeAdded) >= (NOW() - INTERVAL 15 MINUTE)
I'm just not certain of the correct syntax?
This will do the work (tested in MySQL Workbench):
SELECT * FROM OrderEvents WHERE Processed = 0 GROUP BY OrderID
HAVING MAX(TimeAdded) < (NOW() - INTERVAL 15 MINUTE);
I think it's something along these lines:
SELECT OrderID
FROM OrderEvents
WHERE Processed=0
GROUP BY OrderID
HAVING MAX(TimeAdded) < (NOW() - 1500);
Bear in mind, that I'm working blind here. I think 1500 is correct, for the function now() used in a numeric context. http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now