Search between two dates with specific time with each date - mysql

I have two dates. 2019-01-01(fromDate) and 2019-01-10(toDate). And now I want to search only the 13:00 to 16:00 time of each date. May I ask if is it possible using query only? Any answer is much appreciated
SELECT *
FROM table
WHERE fromDate >= 2019-01-01 AND toDate <= 2019-01-10

You can try to use STR_TO_DATE function with the format and HOUR function.
SELECT *
FROM table
WHERE
fromDate >= STR_TO_DATE('2019-01-01', '%Y-%m-%d')
AND
toDate <= STR_TO_DATE('2019-01-10', '%Y-%m-%d')
AND
(HOUR(fromDate) BETWEEN 13 AND 16 OR HOUR(toDate) BETWEEN 13 AND 16)

Use separate conditions on the date and on the time:
SELECT *
FROM table
WHERE fromDate >= '2019-01-01' AND
toDate < '2019-01-11' and
time(fromdate) between '13:00:00' and '16:00:00' and
time(todate) between '13:00:00' and '16:00:00;
Or, if you don't want 16:00:00 exactly, you can use hour():
SELECT *
FROM table
WHERE fromDate >= '2019-01-01' AND
toDate < '2019-01-11' and
hour(fromdate) in (13, 14, 15) and
hour(todate) in (13, 14, 15)

Related

Get yesterday date in SQL

i am try to request date only yesterday but without success...
My query request.
SELECT registeredDaySell FROM new_sell WHERE DATE_SUB(CURDATE(), INTERVAL 1 DAY)
My date is organized this way.
16 September, 2017
Thanks for helping me out.
subdate(now(),1) will return yesterdays timestamp
The below code will select all rows with yesterday's timestamp from employee_login page
Select * FROM `employee_login` WHERE `dattime` <= subdate(now(),1) AND `dattime` > subdate(now(),2)
The below code will display yesterday's timestamp
Select subdate(now(),1) ,subdate(now(),2))
This will give
SELECT producFinalPrice
FROM new_sell
WHERE WEEK (date) = WEEK( current_date ) - 1
As #Gordon mentioned, you should consider storing your dates either in some date type column, or possibly as a UNIX timestamp (seconds since the epoch). A possible workaround here would be to use STR_TO_DATE to convert your string dates to bona fide dates on the fly.
SELECT
producFinalPrice
FROM new_sell
WHERE
STR_TO_DATE(date_col, '%d %M, %Y') = DATE_SUB(CURDATE(), INTERVAL 1 DAY)
This assumes that date_col is the name of the column in your table which contains string dates.
SELECT producFinalPrice FROM new_sell
WHERE where date >= DATEADD(day, -1, convert(date, GETDATE()))
and date < convert(date, GETDATE())
-1 equates to "today" minus 1 day. You can change that number to get the number of days that you want to go back if further than 1.

SQL: Query periods of time given date

I have a list of periods during a year, and they are the same every year. You can think of it as a Season. They have a startDate and a endDate.
Because there can be Seasons that leap each other, what I need to to is query all the matching Seasons given a date, no matter what year.
As an example:
Season1: from 1st of January to 10th of January
Season2: from 6th of January to 8th of January
Season3: from 11th of January to 20th of January
Given the date 7th of January, I'd need to retrieve the Season1 and Season2.
I've tried converting all dates to the same year, but It doesn't work when the Start Date of a season in "later" than the End Date (for example, there's a period starting on November and ending of February).
Thanks in advance for the help.
Edit, sample data:
StartDate EndDate SeasonId
2000-08-01 2000-08-31 4
2000-12-29 2000-01-02 3
2000-06-01 2000-07-30 3
2000-09-01 2000-09-30 3
2000-01-06 2000-01-08 3
2000-04-07 2000-04-17 3
2000-04-28 2000-05-01 3
2000-06-02 2000-06-05 3
2000-06-23 2000-06-25 3
2000-09-08 2000-09-11 3
2000-09-22 2000-09-25 3
2000-10-12 2000-10-15 3
2000-11-01 2000-11-05 3
2000-12-01 2000-12-10 3
2000-12-22 2000-12-26 3
2000-03-01 2000-05-31 2
2000-10-01 2000-10-31 2
2000-11-01 2000-02-28 1
And I'd need, for example, the season for the date 2000-02-08, and retrieve seasonId = 1, or the date 2000-10-13and retrive seasonId = 3, seasonId = 2
I would do it in 2 'options': (the following SQL assumes you already got rid of the year in the table, and left only month-date format. )
select ... from seasons s where
(s.startDate <= s.endDate and s.startDate <= #mydate and s.endDate >= #mydate) or
(s.startDate > s.endDate and s.startDate >= #mydate and s.endDate <= #mydate)
You could query like this for the Season1:
select * from myTable where (month(myDate) = 1 and DAY(myDate) between 1 and 10)
If you have a season in more than one month, like start date January 20th, and finish date Febrery 10th, you could query this way:
select * from myTable where (month(myDate) = 1 and DAY(myDate) >= 20) or (month(myDate) = 2 and DAY(myDate) <= 10)
UPDATED WITH YOUR UPDATE
It is a little bit tricky, but it should work...
select * from seasons_table
where cast(cast(day(myDate) as char) + '/' + cast(month(myDate) as char) + '/' + '2000' as date) between
cast(cast(day(StartDate) as char) + '/' + cast(month(StartDate) as char) + '/' + '2000' as date) and
cast(cast(day(EndDate) as char) + '/' + cast(month(EndDate) as char) + '/' + '2000' as date)
given tblSeason with columns Id, startdate, enddate and your date as #myDate you would query as
Select Id From tblSeason WHERE #myDate BETWEEN startdate AND enddate
would give list of Id's of the seasons that match.
if you can't work from that, please give more information in your examples as to the structure you are querying and the expected outcome.
*Edit to ignore the year part you could do similar to
Declare #myDate datetime = '2016-10-13'
SELECT [StartDate]
,[EndDate]
,[SeasonId]
FROM [dbo].[Table_1]
where DATEPART(dy, #myDate) >= DATEPART(dy,StartDate)
AND (DATEPART(dy,#myDate) =< DATEPART(dy,EndDate) OR DATEPART(dy,StartDate) > DATEPART(dy,EndDate))
Why are you including the year in the table? That seems strange.
In any case, you only care about the MM-DD format, so use date_format() to convert the values to strings:
select t.*
from t
where (start_date <= end_date and
date_format(#date, '%m-%d') >= date_format(start_date, '%m-%d') and
date_format(#date, '%m-%d') <= date_format(end_date, '%m-%d')
) or
(start_date > end_date and
date_format(#date, '%m-%d') <= date_format(start_date, '%m-%d') and
date_format(#date, '%m-%d') >= date_format(end_date, '%m-%d')
);
The strings are fine for comparison, because you are only looking at the month and day components of the date.
Given the nature of your problem, I would recommend that you store start_date and end_date in a non-date format, such as MM-DD.

SQL query to find the previous date, current date and next date

If the current date is 3/12/2015, then I need to get the files from dates 2/12/2015, 3/12/2015, 4/12/2015. Can anyone tell me an idea for how to do it?
<%
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433/CubeHomeTrans","sa","softex");
Statement statement = con.createStatement() ;
ResultSet resultset = statement.executeQuery("
select file from tablename
where date >= DATEADD(day, -1, convert(date, GETDATE()))
and date <= DATEADD(day, +1, convert(date, GETDATE()))") ;
while(resultset.next())
{
String datee =resultset.getString("Date");
out.println(datee);
}
}
catch(SQLException ex){
System.out.println("exception--"+ex);
}
%>
This is the query I have done, but it's erroneous. I need to get the previous date, current date and next date.
Use DATE_ADD() And DATE_SUB() functions:
Try this:
SELECT FILE, DATE
FROM ForgeRock
WHERE STR_TO_DATE(DATE, '%d/%m/%Y') >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)
AND STR_TO_DATE(DATE, '%d/%m/%Y') <= DATE_ADD(CURRENT_DATE(), INTERVAL 1 DAY);
Check the SQL FIDDLE DEMO
::OUTPUT::
| file | DATE |
|------|------------|
| dda | 31/12/2015 |
| ass | 01/01/2016 |
| sde | 02/01/2016 |
Simplest way to get all these dates are as below:-
CURRENT DATE
SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
NEXT DAY DATE (Adding 1 to the dateadd parameter for one day ahead)
SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1)
YESTERDAY DATE (Removing 1 from the datediff parameter for one day back)
SELECT DATEADD(day, DATEDIFF(day, 1, GETDATE()), 0)
If you go through the link here, you will get an amazing way of explanation for getting date. It will clear your logic and will be useful for future reference too.
Hope that helps you
You can use dateAdd function
syntax
DATEADD(datepart,number,date)
i.e for current date
select GETDATE()
for yesterday
select DATEADD(D,-1,GETDATE())
for tomorrow
select DATEADD(D,1,GETDATE())
so, your query should be like
select file from tablename
where date >= DATEADD(D,-1,GETDATE())
and date <= DATEADD(D,1,GETDATE())
current date
date = (SELECT CONVERT(char(10), GetDate(),126))
yesterday
date = (SELECT dateadd(day,datediff(day,1,GETDATE()),0))
next day
date= SELECT DATEADD(day, 1,(convert(date, GETDATE())))

Get data between StartDate & EndDate when dates available bewteen two days?

insert into mytable values
('100', '2015-07-14', '2015-07-25'),
('200', '2015-07-28', '2015-07-30')
I need result like below when i search in the above table
example:
2015-07-13 to 2015-07-29 (not available)
2015-07-15 to 2015-07-22 (available)
I try like below query
select * from mytable where
valid_from <= '2015-07-29' and valid_to >= '2015-07-13'
But it showing results is available.
Here Date's 13, 26, & 27 is not in the table.
Try this code
select * from mytable where
(valid_to between '2015-07-29' and '2015-07-13')
and
(valid_from between '2015-07-29' and '2015-07-13');
and I suggest you to use date in UNIX time stamp (Epoch format).
Just add some more constraints to the query:
select * from mytable where
valid_to >= '2015-07-29' and valid_to <= '2015-07-13' and valid_from >= '2015-07-29' and valid_from <= '2015-07-13';

SQL SERVER 2008 Date difference

I have a column name logdate which has dates in following format
2011-01-04 23:35:44.000
I want to select other columns in between 1st June 2011 till 30th June 2011 so the query should be
select * from abc where logdate = ?
You can use >= and <:
SELECT *
FROM abc
WHERE logdate >= '20110601' AND logdate < '20110701'
There are many ways to manipulate SQL datetimes and strings that represent SQL datetimes:
http://msdn.microsoft.com/en-us/library/ms186724(v=sql.105).aspx
A very straightforward way to do this would be to use >= < operators.
SELECT *
FROM abc
WHERE logdate >= '20110601'
AND logdate < '20110701'
The reason you want to use < July 1 as opposed to <= June 30 is that the string parsing on a date assumes it is midnight on that date, and it will exclude any values later than June 30 at 12 AM.
Assuming that LogDate is a DateTime column, you can use the following query to get the full range of the month:
WHERE logdate >= '2011-06-01' AND logdate < '2011-07-01'