SQL Select between 2 times that cross over days - sql

Hi i have been trying to put an SQL query together to pull data from 20:00 last night to 8 am today
what i currntly have is however this only selects between 20:00 and 24 because it's only selecting last night what would be the best way to get the results i am looking for?
SELECT COUNT(CardID) AS CardCOUNT
FROM ReaderData
WHERE (controllerID = 28) AND (ReaderTime BETWEEN '20:00:00' AND '08:00:00') AND (CardID = 'fffffff0') AND (DATEDIFF(DAY, DATEADD(DAY, - 1,
CURRENT_TIMESTAMP), dtReading) = 0)

You have split the time from the date so you have to check one time interval for yesterday and another for today.
If you are on SQL Server 2008 and have stored only the date part in dtReading you could use something like this.
select count(R.CardID) as CardCount
from ReaderData as R
where controllerID = 28 and
(
(
R.dtReading = cast(dateadd(day, -1, getdate()) as date) and
R.ReaderTime >= '20:00:00'
) or
(
R.dtReading = cast(getdate() as date) and
R.ReaderTime < '08:00:00'
)
)
Update
With the time values in dtReading it is easier.
Remove the time part from getdate() by casting to date then add the number of hours you want to create the datetime values you want to compare against.
select count(R.CardID) as CardCount
from ReaderData as R
where controllerID = 28 and
R.dtReading >= dateadd(hour, 20, dateadd(day, -1, cast(cast(getdate() as date) as datetime))) and
R.dtReading < dateadd(hour, 8, cast(cast(getdate() as date) as datetime))

Related

SQL Server, filter for max date and max date minus 7 days

I'm trying to design a view and apply several conditions on my timestamp (datetime): last date and last date minus 7 days.
This works fine for the last date:
SELECT *
FROM table
WHERE timestamp = (SELECT MAX(timestamp) FROM table)
I couldn't figure out the way to add minus 7 days so far.
I tried, for instance
SELECT *
FROM table
WHERE (timestamp = (SELECT MAX(timestamp) FROM table)) OR (timestamp = (SELECT DATEADD(DAY, -7, MAX(timestamp)) FROM table)
and some other variations, including GETDATE() instead of MAX, however, I'm getting the execution timeout messages.
Please let me know what logic should I follow in this case.
Data looks like this, but there's more of it :)
So I want to get data only for rows with 29/11/2019 and 22/11/2019. I have an additional requirement for filtering for factors, but it's a simple one.
If you care about dates, then perhaps you want:
select t.*
from t cross join
(select max(timestamp) as max_timestamp from t) tt
where (t.timestamp >= convert(date, max_timestamp) and
t.timestamp < dateadd(day, 1, convert(date, max_timestamp))
) or
(t.timestamp >= dateadd(day, -7, convert(date, max_timestamp)) and
t.timestamp < dateadd(day, -6, convert(date, max_timestamp))
);
So I ended up with the next code:
SELECT *
FROM table
WHERE (timestamp >= CAST(DATEADD(DAY, - 1, GETDATE()) AS datetime)) AND (timestamp < CAST(GETDATE() AS DATETIME)) OR
(timestamp >= CAST(DATEADD(DAY, - 8, GETDATE()) AS datetime)) AND (timestamp < CAST(DATEADD(day, - 7, GETDATE()) AS DATETIME)) AND (Factor1 = 'Criteria1' OR
Factor2 = 'Criteria2')
Not sure if it's the best or the most elegant solution, but it works for me.

Query for results between now and 7 days from now

I know there are similar answers to this, but none of them have worked for me. I have a query with a date field in it. I want to filter the results for the next 7 days. It works if I specify the dates i.e date between '2019-07-18' AND '2019-07-25' but I need it to be more generic.
Thanks in advance!
Here are a few things I've tried:
CAST( datefield AS DATE ) > DATEADD( DAY, +7, CAST( GETDATE() AS DATE ))
WHERE GETDATE()+7
AND DATEADD(dd, -7, datefield) <= CAST(datefield AS DATETIME)
You can use logic like this:
where datefield >= dateadd(day, 1, cast(getdate() as date)) and
datefield < dateadd(day, 8, cast(getdate() as date))
This assumes you are using SQL Server (based on your syntax) and that you don't want today's data ("next 7 days").
You didnt specify what SQL you are using so this might not be fine for you.
WHERE datefield BETWEEN SYSDATE AND SYSDATE + 7
datefield between today and next 7 days
WHERE
CAST(datefield AS DATE) <= DATEADD(DAY, 7, CAST(GETDATE() AS DATE ))
AND CAST(datefield AS DATE) >= CAST(GETDATE() AS DATE )

select all from table using date with time

how can I get the last recorded data of the time 23:59 from yesterday and the day before?
my code doesn't have a filter of the time yet so it only shows all the data from yesterday and the day before.
select *
from tbl_Total
where date between DATEADD(day, -3, GETDATE()) AND DATEADD(day, -1, GETDATE())
In your case,
select * from tbl_Total as of timestamp timestamp '2017-07-19 23:59:59'
and
select * from tbl_Total as of timestamp timestamp '2017-07-18 23:59:59'
Try this
select *
from tbl_Total
where date between dateadd(day,-3,convert(varchar(10),getdate(),112)) AND dateadd(day,-3,convert(varchar(10),getdate(),112)+ ' 23:59:59:997' )
This query will return yestarday date with time 23:59:59.
SELECT CAST(CAST(CAST(DATEADD(day, -1, GETDATE()) as DATE) as varchar(12)) +' 23:59:59' as datetime2)
So you can use it in your query:
select *
from tbl_Total
where date between DATEADD(day, -3, GETDATE()) AND CAST(CAST(CAST(DATEADD(day, -1, GETDATE()) as DATE) as varchar(12)) +' 23:59:59' as datetime2)
EDIT: More elegant way:
SELECT DATEADD(second, -1, DATEADD(dd, DATEDIFF(dd,0,GETDATE()),0))
This query returns yesterday date with time 23:59:59.
EDIT2: If you want to return the day before with time 23:59:59 you need to use this query:
SELECT DATEADD(second, -1, DATEADD(dd, DATEDIFF(dd,1,GETDATE()),0))
If you want to obtain any other day you can change number 2 and test it.
Assuming you don't know the exact time you can get the latest rows using ROW_NUMBER:
with cte as
( select *,
row_number() -- for each day sorted descending
over (partition by DATEADD(dd, DATEDIFF(dd,0,GETDATE()),0)
order by date desc) as rn
from tbl_Total
where -- yesterday between 23:59 and 23:59:99.999
( date >= DATEADD(dd, DATEDIFF(dd,0,GETDATE()),0) - (1.0/1440)
and date < DATEADD(dd, DATEDIFF(dd,0,GETDATE()),0)
)
or -- day before yesterday between 23:59 and 23:59:99.999
( date >= DATEADD(dd, DATEDIFF(dd,1,GETDATE()),0) - (1.0/1440)
and date < DATEADD(dd, DATEDIFF(dd,1,GETDATE()),0)
)
)
select * from cte
where rn = 1 --latest row only

Why do I get different results with this SQL Date Part and date parameters

When I run this where clause on my table I get 2 different results and to me its seems like I should get the same number of records back.
The one I'm using just a static date to test and the other should also retrieve the same results where I'm trying to get last month results
I idea the query is a report that will automatic load the previous months records.
WHERE
(OrderReceiptedDate >= '2015-03-01')
AND (OrderReceiptedDate <= '2015-03-31')
WHERE
(DATEPART(mm, OrderReceiptedDate) = DATEPART(mm, DATEADD(mm, - 1, GETDATE())))
AND
(DATEPART(yy, OrderReceiptedDate) = DATEPART(yy, DATEADD(mm, - 1, GETDATE())))
These are the two statements
WHERE (OrderReceiptedDate >= '2015-03-01' AND
OrderReceiptedDate <= '2015-03-31'
)
WHERE (DATEPART(month, OrderReceiptedDate) = DATEPART(month, DATEADD(month, - 1, GETDATE()))) AND
(DATEPART(year, OrderReceiptedDate) = DATEPART(year, DATEADD(month, - 1, GETDATE())))
Given that today is April 2015, you are expecting that both of these get all dates for March. And, they would, if your dates had no time components. The problem is that almost any datetime on March 31st is not going to match the first condition. The one exception is exactly at midnight: 2015-03-01 00:00:00.000.
The first is better written as:
WHERE (OrderReceiptedDate >= '2015-03-01' AND
OrderReceiptedDate < '2015-04-01'
)
A better way to write "get me last months date" is something like:
WHERE OrderReceiptedDate >= dateadd(month, -1, cast(getdate() - day(getdate()) + 1 as date)) and
OrderReceiptedDate < cast(getdate() - day(getdate()) + 1 as date)
This does all the calculations on getdate() so the query could still take advantage of an index on OrderReceiptDate.

SQL statement to select all rows from previous day

I am looking for a good SQL Statement to select all rows from the previous day from one table. The table holds one datetime column. I am using SQL Server 2005.
get today no time:
SELECT dateadd(day,datediff(day,0,GETDATE()),0)
get yestersday no time:
SELECT dateadd(day,datediff(day,1,GETDATE()),0)
query for all of rows from only yesterday:
select
*
from yourTable
WHERE YourDate >= dateadd(day,datediff(day,1,GETDATE()),0)
AND YourDate < dateadd(day,datediff(day,0,GETDATE()),0)
To get the "today" value in SQL:
convert(date, GETDATE())
To get "yesterday":
DATEADD(day, -1, convert(date, GETDATE()))
To get "today minus X days": change the -1 into -X.
So for all yesterday's rows, you get:
select * from tablename
where date >= DATEADD(day, -1, convert(date, GETDATE()))
and date < convert(date, GETDATE())
It's seems the obvious answer was missing. To get all data from a table (Ttable) where the column (DatetimeColumn) is a datetime with a timestamp the following query can be used:
SELECT * FROM Ttable
WHERE DATEDIFF(day,Ttable.DatetimeColumn ,GETDATE()) = 1 -- yesterday
This can easily be changed to today, last month, last year, etc.
SELECT * from table_name where date_field = DATE_SUB(CURRENT_DATE(),INTERVAL 1 DAY);
Its a really old thread, but here is my take on it.
Rather than 2 different clauses, one greater than and less than. I use this below syntax for selecting records from A date. If you want a date range then previous answers are the way to go.
SELECT * FROM TABLE_NAME WHERE
DATEDIFF(DAY, DATEADD(DAY, X , CURRENT_TIMESTAMP), <column_name>) = 0
In the above case X will be -1 for yesterday's records
This should do it:
WHERE `date` = CURDATE() - INTERVAL 1 DAY
Can't test it right now, but:
select * from tablename where date >= dateadd(day, datediff(day, 1, getdate()), 0) and date < dateadd(day, datediff(day, 0, getdate()), 0)
In SQL Server do like this:
where cast(columnName as date) = cast(getdate() -1 as date)
You should cast both sides of the expression to date to avoid issues with time formatting.
If you need to control interval in more detail, then you should try something like:
declare #start datetime = cast(getdate() - 1 as date)
declare #end datetime = cast(getdate() - 1 as date)
set #end = dateadd(second, 86399, #end)
Another way to tell it "Yesterday"...
Select * from TABLE
where Day(DateField) = (Day(GetDate())-1)
and Month(DateField) = (Month(GetDate()))
and Year(DateField) = (Year(getdate()))
This conceivably won't work well on January 1, as well as the first day of every month. But on the fly it's effective.
Well, its easier to cast the datetime column to date and than compare.
SELECT * FROM TABLE_NAME WHERE cast(COLUMN_NAME as date) =
dateadd(day,0, convert(date, getdate(), 105))
A simple alternative
Select GETDATE() - 1
Change 1 to go back that many number of days
PS : This gives you timestamp accuracy.
This worked a charm:
SELECT * FROM mytable WHERE date(mydate) = DATE_SUB(CURDATE(), INTERVAL 1 DAY);
subdate(now(),1) will return yesterdays timestamp
The below code will select all rows with yesterday's timestamp
Select * FROM `login` WHERE `dattime` <= subdate(now(),1) AND `dattime` > subdate(now(),2)