I am using the below SQL Query to get the data from a table for the last 7 days.
SELECT *
FROM emp
WHERE date >= (SELECT CONVERT (VARCHAR(10), Getdate() - 6, 101))
AND date <= (SELECT CONVERT (VARCHAR(10), Getdate(), 101))
ORDER BY date
The data in the table is also holding the last year data.
Problem is I am getting the output with Date column as
10/11/2013
10/12/2012
10/12/2013
10/13/2012
10/13/2013
10/14/2012
10/14/2013
10/15/2012
10/15/2013
10/16/2012
10/16/2013
10/17/2012
10/17/2013
I don't want the output of 2012
year. Please suggest on how to change the query to get the data for the last 7 days of this year.
We use system function now() to get the latest datetime value, and INTERVAL clause to calculate a date 7 days in the past.
SELECT * FROM product WHERE pdate >= DATEADD(day, -30, getdate()).
Instead of converting a date
to a varchar
and comparing a varchar
against a varchar
. Convert the varchar
to a datetime
and then compare that way.
SELECT
*
FROM
emp
WHERE
convert(datetime, date, 101) BETWEEN (Getdate() - 6) AND Getdate()
ORDER BY
date
Why convert to varchar when processing dates? Try this instead:
DECLARE @Now DATETIME = GETDATE();
DECLARE @7DaysAgo DATETIME = DATEADD(day,-7,@Now);
SELECT *
FROM emp
WHERE date BETWEEN @7DaysAgo AND @Now
ORDER BY date
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With