How do I compare against the current week using SQL Server? - sql

How do I compare an SQL Server date column against the current week?
For instance:
WHERE [Order].SubmittedDate = *THIS WEEK*

You could convert your date to a week number and compare this to the week number from the current date. Likewise, you'll need to compare the year as well, so that you don't get last year's weeks.
WHERE DATEPART(wk, [Order].SubmittedDate) = DATEPART(wk, GETDATE())
AND DATEPART(yy, [Order].SubmittedDate) = DATEPART(yy, GETDATE())

Assuming you are meaning always "this week" and there are no records with Submitted dates in the future, which I imagine could be the case you can do:
WHERE [Order].SubmittedDate >= DATEADD(dd, -(DATEPART(dw, GETDATE()) -1), GETDATE())
If dates do go into the future, the full restriction to this week is:
WHERE [Order].SubmittedDate >= DATEADD(dd, -(DATEPART(dw, GETDATE()) -1), GETDATE())
AND [Order].SubmittedDate < CAST(CONVERT(VARCHAR(10), DATEADD(dd, (8 - DATEPART(dw, GETDATE())), GETDATE()), 120) AS DATETIME)
I'd strongly recommend using a clause based on a start and end date like this, as it will allow efficient index use so should perform better.

Try this:
WHERE [Order].SubmittedDate BETWEEN
DATEADD(d, - DATEPART(dw, GETDATE()) + 1, GETDATE()) AND
DATEADD(d, 7 - DATEPART(dw, GETDATE()) , GETDATE())
Maybe this can run faster, as doesn't needs to be evaluated everytime:
DECLARE #StartDate DATETIME,
#EndDate DATETIME
SELECT #StartDate = DATEADD(d, - DATEPART(dw, GETDATE()) + 1, GETDATE()),
#EndDate = DATEADD(d, 8 - DATEPART(dw, GETDATE()) , GETDATE())
-- // Strip time part, so week starts on Sunday 00:00
SELECT #StartDate = CAST(FLOOR(CAST(#StartDate AS FLOAT)) AS DATETIME),
#EndDate = CAST(FLOOR(CAST(#EndDate AS FLOAT)) AS DATETIME)
...
WHERE [Order].SubmittedDate >= #StartDate AND [Order].SubmittedDate < #EndDate

Related

Get data from last month in SQL Server

I checked Get the records of last month in SQL server and it did not work!
I try to get the records of last month based on my database table and column issue_date.
What's the SQL query to do this?
For clarification, today (27-April-18) I want to get all records from March-18.
I have the issue_date in the format that I convert to date but below code gives me all records from 01-March-2018 to and including today.
DATEPART(month, CONVERT (VARCHAR(11),DATEADD(day,wo_header.issue_date,`1971/12/31`),106)) = DATEPART(month, DATEADD(month, -1, getdate()))
To get firstDay and lastDay of previous month
DECLARE #FirstDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -(DAY(DATEADD(m, -1, GETDATE() - 2))), DATEADD(m, -1, GETDATE() - 1))),
#LastDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -(DAY(GETDATE())), GETDATE()))
SELECT #FirstDayOfLastMonth, #LastDayOfLastMonth
Your required Query
SELECT *
FROM TABLE
WHERE CAST(issue_date AS DATE) BETWEEN CONVERT(DATE, DATEADD(d, -(DAY(DATEADD(m, -1, GETDATE() - 2))), DATEADD(m, -1, GETDATE() - 1))) AND CONVERT(DATE, DATEADD(d, -(DAY(GETDATE())), GETDATE()))
Perhaps the easiest method is eomonth(). If there is no time component on issuedate:
where issuedate > eomonth(getdate(), -2) and
issuedate <= eomonth(getdate(), -1)
If there is a time component:
where issuedate >= dateadd(day, 1, cast(eomonth(getdate(), -2) as date)) and
issuedate < dateadd(day, 1, cast(eomonth(getdate(), -1) as date))
Without eomonth, I would do:
where issuedate < cast(dateadd(day, 1 - day(getdate()), getdate()) as date) and
issuedate >= dateadd(month, -1, cast(dateadd(day, 1 - day(getdate()), getdate()) as date))
The code I figured out is not pretty but it works. It first adds extra column with the month number to the SELECT portion of my code:
Month(CONVERT (VARCHAR(11),DATEADD(day,wo_header.closing_date,'1971/12/31'),106)) As Month
And than is used for WHERE statement:
Month(CONVERT (VARCHAR(11),DATEADD(day,wo_header.closing_date,'1971/12/31'),106)) = month(getdate())-1
So for anyone like me working in SQL report kind-of environment it should work.

Get last date of the previous month Transact-SQL

I am trying to fetch data for the previous full month, but the data from the last day is not fetching.
Output: Previous Month is April and this condition only retrieving data up to 29th April. Data for 30th April is missing.
Can please someone help me to correct this.
OLH.DateStamp > CONVERT(VARCHAR,DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0),101)
And
OLH.DateStamp < CONVERT(VARCHAR,DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1),101))
Thanks in advance
The simplest way to get data for the previous month is:
DATEDIFF(month, OLH.DateStamp, GETDATE()) = 1
However, that does not use indexes. So, a better method is:
OLH.DateStamp >= DATEADD(MONTH, -1, DATEADD(DAY, 1 - DAY(GETDATE()), CAST(GETDATE() as DATE))) AND
OLH.DateStamp < DATEADD(DAY, 1 - DAY(GETDATE()), CAST(GETDATE() as DATE))
The expression:
DATEADD(DAY, 1 - DAY(GETDATE), CAST(GETDATE() as DATE))
returns midnight on the first day of the current month.
You should try last day of Month Should be <= OLH.Datestamp
To get Desired Output you are Looking for:
--Use It In Where Clause
DECLARE #FirstDayOfLastMonth
DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, -1, GETDATE() -
2)) ), DATEADD(m, -1, GETDATE() - 1)))
,#LastDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(GETDATE()) ), GETDATE()))
OLH.DateStamp >= CONVERT(VARCHAR, #FirstDayOfLastMonth , 101) AND
OLH.DateStamp <= CONVERT(VARCHAR, #LastDayOfLastMonth , 101)

Accumulating data from previous year

I'm having trouble with finding a solution for below SQL-query. My first query should and does the trick of accumulating amount of last year's data.
CASE
WHEN rehuv.VER_DATUM >= dateadd(year, -1, dateadd(month, -datepart(month, #STARTDATE) + 1, #STARTDATE))
AND rehuv.VER_DATUM <= DATEADD(year, -1, #ENDDATE) THEN rehuv.BELOPP ELSE 0
END AS PREVIOUS_YEAR_ACC
But when I try to accumulate data within a specific time interval (I want the same time interval as #startdate -> #enddate but one year backwards). Sql-query:
CASE
WHEN rehuv.VER_DATUM >= DATEADD(year, -1, #STARTDATE)
AND rehuv.VER_DATUM <= DATEADD(year, -1, #ENDDATE) THEN rehuv.BELOPP ELSE 0
END AS PREVIOUS_YEAR_MONTH
Thank you in advance!
Best regards,
Simon
If you want the monthly sum of last year, you can try this:
DECLARE #STARTDATE DATETIME;
DECLARE #ENDDATE DATETIME;
SET #STARTDATE='2015-1-1';
SET #ENDDATE='2015-5-1';
DECLARE #LAST_YEAR DATE;
SET #LAST_YEAR = DATEADD(YEAR, -1, DATEADD(DAY,
DATEPART(DAYOFYEAR, GETDATE())*-1+1, CONVERT(DATE, GETDATE())));
SELECT DATEADD(MONTH, DATEPART(MONTH, VER_DATUM), #LAST_YEAR) MONTH, SUM(CASE
WHEN REHUV.VER_DATUM >= DATEADD(YEAR, -1, #STARTDATE)
AND REHUV.VER_DATUM <= DATEADD(YEAR, -1, #ENDDATE)
THEN REHUV.BELOPP ELSE 0
END ) AS PREVIOUS_YEAR_MONTH
FROM REHUV
GROUP BY DATEPART(MONTH, VER_DATUM)

Conditional where statement: select different time period when query date varies

I have a query need to select different time period. The logic is:
if today is Tuesday, select Saturday 00:00:00 ~ Monday 23:99;
if today is other weekdays, select the previous working day (00:00:00 ~ 23:99).
Here is the query I have:
Select *
From ...
WHERE
(DATENAME(DW,GETDATE())= 'Tuesday'
AND (<#SalesDate> BETWEEN DATEADD(DAY, -3, GETDATE()) and DATEADD(DAY, -1, GETDATE())))
OR
(DATENAME(DW,GETDATE())<> 'Tuesday'
AND (<#SalesDate> BETWEEN DATEADD(DAY, -1, GETDATE())and DATEADD(DAY, -1, GETDATE())))
It didn't return the result that I want. Anyone can help me? thank you.
BETWEEN is a bit finicky when it comes to date datatypes. See this question.
GETDATE() will return the time for today. You need to strips it off.
-- Today's date, stripped of time
DECLARE #Today datetime = CONVERT(datetime,CONVERT(date,GETDATE()))
Select *
From ...
WHERE
(DATENAME(DW,GETDATE())= 'Tuesday'
AND (#SalesDate >= DATEADD(DAY, -3, #Today) and #SalesDate < DATEADD(DAY, -1, #Today)))
OR
(DATENAME(DW,GETDATE())<> 'Tuesday'
AND (#SalesDate >= DATEADD(DAY, -1, #Today) and #SalesDate < DATEADD(DAY, -1, #Today)))

How do I find data from this day exactly one year ago?

Right now I have:
year(epe_curremploymentdate) = year(DATEADD(year, -1, SYSDATETIME()))
But that is giving me everything from last year. All I want is the data from today's date, one year ago.
It should be:
epe_curremploymentdate = DATEADD(year, -1, GETDATE())
Don't check for year in your where clause.
EDIT:
Simple: use
cast(epe_curremploymentdate AS DATE) = cast(DATEADD(year, -1,
GETDATE()) AS DATE)
That is, if you are using SQL Server 2008 and above.
This should get you to where you need to go:
Declare #StartDate datetime, #EndDate datetime
-- #StartDate is midnight on today's date, last year
set #StartDate = Convert(date, (DATEADD(year, -1, getdate())))
set #EndDate = DATEADD(Day, 1, #StartDate)
select *
from YourTable
where epe_curremploymentdate >= #StartDate
and epe_curremploymentdate < #EndDate
-- This where clause will get you everything that happened at any time
-- on today's date last year.
Date today:
select getdate()
date one year ago:
select dateadd(year, -1, getdate())
Date one year and one day ago:
select dateadd(d, -1 , dateadd(year, -1, getdate()))
UPDATE:
select *
from
epe_curremploymentdate = dateadd(year, -1, CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME))
This will give you a list of all employees who started working exactly from a year ago.
Hope this helps!!!
If you have other fields that show as datetime with the time part as 00:00:00.000, to do joins you can use the below
dateadd(yy,-1,datediff(d,0,getdate()))
epe_curremploymentdate = DATEADD(year, -1, GETDATE())