Accumulating data from previous year - sql

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)

Related

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)

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)))

query for first and last day of month

If I have the name of the month, how can I have the first and last day of that month in SQL?
I have this query to returns the month names:
DECLARE #StartDate DATETIME,
#EndDate DATETIME;
SELECT #StartDate = '20110501'
,#EndDate = '20110801';
SELECT DATENAME(MONTH, DATEADD(MONTH, x.number, #StartDate)) AS MonthName
FROM master.dbo.spt_values x
WHERE x.type = 'P'
AND x.number <= DATEDIFF(MONTH, #StartDate, #EndDate)
Result:
Now, how can i get the first and last day of that months? changing the query.
If you want a more general and simple solution:
DECLARE #startdate AS DATETIME = GETDATE()
SELECT
DATEADD(MONTH, DATEDIFF(MONTH, 0, #startdate) , 0) as startMonth,
DATEADD(SECOND, -1, DATEADD(MONTH, 1, DATEADD(MONTH, DATEDIFF(MONTH, 0, #startdate) , 0) ) ) as endMonth
Gives the result:
startMonth endMonth
----------------------- -----------------------
2013-06-01 00:00:00.000 2013-06-30 23:59:59.000
Try this :-
DECLARE #StartDate DATETIME,
#EndDate DATETIME;
SELECT #StartDate = '20110501'
,#EndDate = '20110801';
SELECT DATENAME(MONTH, DATEADD(MONTH, x.number, #StartDate)) AS MonthName,
CONVERT(VARCHAR(25),
DATEADD(dd,-(DAY(DATEADD(MONTH, x.number, #StartDate))-1),DATEADD(MONTH, x.number, #StartDate)),101) as FirstDay,
CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,DATEADD(MONTH, x.number, #StartDate)))),DATEADD(mm,1,DATEADD(MONTH, x.number, #StartDate))),101) as LastDay
FROM master..spt_values x
WHERE x.type = 'P'
AND x.number <= DATEDIFF(MONTH, #StartDate, #EndDate)
Result :-
MonthName FirstDay LastDay
May 05/01/2011 05/31/2011
June 06/01/2011 06/30/2011
July 07/01/2011 07/31/2011
August 08/01/2011 08/31/2011
Result obtained taking the help from this query
This code gives you the first date of Current Month:
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
If you know the Month's number then:
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + #MonthNumber, 0)
Same goes for Month's end date :
SELECT DATEADD(MILLISECOND, -1,
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - ##MonthNumber+ 1, 0))

Finding the list of people who have birthday this week

I am trying to list the people who have birthday this week with this code:
declare #START_DATE date;
set #START_DATE = DATEADD(dd, 1 - DATEPART(dw, getdate()), getdate())
declare #END_DATE date;
set #END_DATE = DATEADD(dd,6, #START_DATE)
set DATEFIRST 1
SELECT #START_DATE as StartDate, Personel.DogumTarihi , #END_DATE as EndDate
,[Adi]
,[Soyadi]
,[BirimAdi]
,[DogumTarihi]
,[MudurlukAdi]
,[Gorevi]
,[CepTelefonu]
,[EvTelefonu]
from Personel
where (
DATEPART(m, Personel.DogumTarihi) = DATEPART(m, #START_DATE)
and DATEPART(DAY, Personel.DogumTarihi) >= DATEPART(DAY, #START_DATE)
and DATEPART(DAY, Personel.DogumTarihi) <= DATEPART(DAY, #END_DATE)
)
OR (
DATEPART(m, Personel.DogumTarihi) = (DATEPART(m, #START_DATE)+ 1)
and DATEPART(DAY, Personel.DogumTarihi) <= DATEPART(DAY, #END_DATE)
)
First I set the start date and calculate the end date according to start date. Then I set Monday as the first day of week.
But everytime I run this, I receive a different Start date. I am quite new to Ms Sql Scripting, I may be doing sth wrong in the declarations but I couldn'd find it. Thanks in advance.
Try this:
SELECT DATEADD(WEEK, DATEDIFF(DAY, 0, GETDATE())/7, 0) FirstDayOfCurrentWeek,
DATEADD(YEAR, DATEDIFF(YEAR, DogumTarihi, GETDATE()), [DogumTarihi]) BirthdayThisYear,
DATEADD(WEEK, 1, DATEADD(WEEK, DATEDIFF(DAY, 0, GETDATE())/7, 0)) FirstDayOfNextWeek
,[Adi]
,[Soyadi]
,[DogumTarihi]
,[BirimAdi]
,[MudurlukAdi]
,[Gorevi]
,[CepTelefonu]
,[EvTelefonu]
FROM Personel
WHERE DATEADD(YEAR, DATEDIFF(YEAR, [DogumTarihi], GETDATE()), [DogumTarihi]) >= DATEADD(WEEK, DATEDIFF(DAY, 0, GETDATE())/7, 0)
AND
DATEADD(YEAR, DATEDIFF(YEAR, [DogumTarihi], GETDATE()), [DogumTarihi]) < DATEADD(WEEK, 1, DATEADD(WEEK, DATEDIFF(DAY, 0, GETDATE())/7, 0))
ok, one more attempt:
where
case when year(#START_DATE) = year(#END_DATE) THEN '1' ELSE CASE WHEN month(#birthdate) = 12 THEN '0' WHEN month(#birthdate) = 1 THEN '1' ELSE '9' END END
+ RIGHT('0' + CONVERT(varchar(2), MONTH(#birthdate)),2)
+ RIGHT('0' + CONVERT(varchar(2), DAY(#birthdate)),2)
between
case when year(#START_DATE) = year(#END_DATE) THEN '1' ELSE '0' END
+ RIGHT('0' + CONVERT(varchar(2), MONTH(#START_DATE)),2)
+ RIGHT('0' + CONVERT(varchar(2), DAY(#START_DATE)),2)
and
'1'
+ RIGHT('0' + CONVERT(varchar(2), MONTH(#END_DATE)),2)
+ RIGHT('0' + CONVERT(varchar(2), DAY(#END_DATE)),2)
sql should let you specify the week directly
DATEPART(ww,GETDATE())
or in oracle: to_char( mydate, 'ww' )
In order to cope with the my problem I revised the code above according to answers:
set DATEFIRST 1
declare #START_DATE date;
set #START_DATE = DATEADD(dd, 1 - DATEPART(dw, getdate()), getdate())
declare #END_DATE date;
set #END_DATE = DATEADD(dd,6, #START_DATE)
SELECT #START_DATE as StartDate,
(case when
(DATEPART(m, #START_DATE) = DATEPART(m, #END_DATE))
then
(case when (DATEPART(DAY, Personel.DogumTarihi) >= DATEPART(DAY, #START_DATE) and DATEPART(DAY, Personel.DogumTarihi) <= DATEPART(DAY, #END_DATE)) then Personel.DogumTarihi else 0 end)
else
(case when DATEPART(m, Personel.DogumTarihi) = DATEPART(m, #START_DATE)
then
(case when (DATEPART(DAY, Personel.DogumTarihi) >= DATEPART(DAY, #START_DATE)) then Personel.DogumTarihi else 0 end)
else
(case when (DATEPART(DAY, Personel.DogumTarihi) <= DATEPART(DAY, #END_DATE)) then Personel.DogumTarihi else 0 end)
end
)
end),
#END_DATE as EndDate, [TCKN]
,[Adi]
,[Soyadi]
,[BirimAdi]
,[DogumTarihi]
,[MudurlukAdi]
,[Gorevi]
,[CepTelefonu]
,[EvTelefonu]
,[VakifTelefonu]
from Personel where
DATEPART(m, #START_DATE) = DATEPART(m, #END_DATE)
OR DATEPART(m, Personel.DogumTarihi) = DATEPART(m, #START_DATE)
OR DATEPART(m, Personel.DogumTarihi) = DATEPART(m, #END_DATE)
Now it is taking the case where "the start and end date of the month are in the same week (like this week)" into account. It looks like it is bringing right results..
Let's have a try:
declare #today datetime
set #today = getdate()
-- erase the hours
set #today = dateadd(hh, -datepart(hh, #today), #today)
-- erase the minutes
set #today = dateadd(mi, -datepart(mi, #today), #today)
-- erase the seconds
set #today = dateadd(ss, -datepart(ss, #today), #today)
-- erase the milliseconds
set #today = dateadd(ms, -datepart(ms, #today), #today)
-- go to start of current week (sunday!)
set #today = dateadd(dd, 1-datepart(dw, #today), #today)
select * from MYTABLE
where DATECOL between
dateadd(yy, datepart(yy, DATECOL) - datepart(yy, #today), #today) and
dateadd(d, 7, dateadd(yy, datepart(yy, DATECOL) - datepart(yy, #today), #today))
Apparently SqlServer 2012 has a DATEFROMPARTS function, in 2005 we will have to use this roundabout way to trim a date.
To select a birthday, I exchange the "today's year" for the record's year. For the end-date of the range I add 7 days to that. Note that you want to search from sunday 0:00 to saturday 23:59.
This will probably still fail if halfway during the week a new year starts and the birthday you want is in the new year.

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

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