Recursive Start of Week Query with SUM - sql-server

I am looking to get the sum of hours worked by week for n weeks in a single result. I came across this little gem that will provide a list of weeks going back n weeks from the current day using a recursive query.
DECLARE #dt DATE = '1900-01-01';
declare #startDate datetime , #endDate datetime
set #startDate = DATEADD(WEEK, DATEDIFF(WEEK, #dt, CURRENT_TIMESTAMP)-10, #dt)
set #endDate = DATEADD(WEEK, DATEDIFF(WEEK, #dt, CURRENT_TIMESTAMP)-1, #dt)
;with T(startday) as
(
select #startDate as startday
union all
select startday + 7
from T
where startday < #endDate
)
select startday as [StartDate], DATEADD(DD, 7, startday) AS [EndDate] from T
If I could use a similar recursive query that would be great. Other wise, I can build a big query with a union of each date range. I have spent more time than I would like to admit on this.
If I try.
DECLARE #monDT DATE = '1900-01-01';
DECLARE #startDate DATETIME , #endDate DATETIME
SET #startDate = DATEADD(WEEK, DATEDIFF(WEEK, #monDT, CURRENT_TIMESTAMP)-10, #monDT)
SET #endDate = DATEADD(WEEK, DATEDIFF(WEEK, #monDT, CURRENT_TIMESTAMP), #monDT)
;WITH T(startDay, endDay, StartDateTime, FinishedDateTime, ActualDurationHours)
AS (
SELECT
#startDate AS startDay,
#endDate AS endDay,
[WorkOrderTrade].[StartDateTime],
[WorkOrderTrade].[FinishedDateTime],
[WorkOrderTrade].[ActualDurationHours]
FROM [WorkOrderTrade]
WHERE [WorkOrderTrade].[TradeContactID] = 783
AND [WorkOrderTrade].[StartDateTime] > #startDate
AND [WorkOrderTrade].[FinishedDateTime] < #endDate
UNION ALL
SELECT
startDay + 7,
endDay,
StartDateTime,
FinishedDateTime,
ActualDurationHours
FROM T
WHERE startDay < #endDate
)
SELECT TOP (100)
startDay,
DATEADD(DD, 7, startday) AS endDay,
SUM(ActualDurationHours)
FROM T
GROUP BY startDay, endDay
It SUMs the total hours across the whole date range as per the recursive portion of the query. I need to come up with a way of filtering the hours in that recursive portion based on the startDay and endDay of each week. Something like the following would be good but you are not allowed to accumulate in the recursive portion.
SELECT
startDay + 7,
StartDateTime,
FinishedDateTime,
(SELECT SUM(ActualDurationHours) FROM [WorkOrderTrade] WHERE [WorkOrderTrade].[TradeContactID] = 783 AND (StartDateTime > startDay AND FinishedDateTime < DATEADD(DD, 7, startDay)))
FROM T
WHERE startDay < #endDate
Is there a way or do I need to build a large UNION query?

Persistence pays off but I had to go out of that box that I was stuck in and use a temporary table and a WHILE loop.
DECLARE #monDT DATE = '1900-01-01';
DECLARE #startDate DATETIME , #endDate DATETIME, #startOfWeek DATETIME
SET #startDate = DATEADD(WEEK, DATEDIFF(WEEK, #monDT, CURRENT_TIMESTAMP)-10, #monDT)
SET #endDate = DATEADD(WEEK, DATEDIFF(WEEK, #monDT, CURRENT_TIMESTAMP)+1, #monDT)
SET #startOfWeek = #startDate
CREATE TABLE #tmpDuration (
StartDate DATETIME,
EndDate DATETIME,
LoggedHours NUMERIC(18,7)
)
WHILE #startOfWeek < #endDate
BEGIN
INSERT INTO #tmpDuration
SELECT
#startOfWeek,
DATEADD(DD, 7, #startOfWeek),
SUM([WorkOrderTrade].[ActualDurationHours])
FROM [WorkOrderTrade]
WHERE [WorkOrderTrade].[TradeContactID] = 783
AND [WorkOrderTrade].[StartDateTime] > #startOfWeek
AND [WorkOrderTrade].[StartDateTime] < DATEADD(DD, 7, #startOfWeek)
SET #startOfWeek = DATEADD(DD, 7, #startOfWeek)
END
SELECT * FROM #tmpDuration
DROP TABLE #tmpDuration

Related

How to declare dates in SQL multiple value

I am trying to create my SQL syntax so that we can have versatile input. I figured out how to do it for one set date and it worked.
my syn is:
DECLARE #MyDay AS VARCHAR(50);
DECLARE #NextDay AS VARCHAR(50);
SET #MyDay = '8/30/2016';
SET #NextDay = DATEADD(d, 1, #MyDay);
However, I'm stuck with how to do it for multiple dates. Ideally I would like to put in a range of date, and from that it will scan the records, i.e. set range between oct 1st and oct 5th.
I'm using SQL Server Management Studio 2008
If you just want a series of days and next days between 8/30/16 and 9/5/16, you can use a derive table method like below.
declare #n int;
declare #StartDate datetime, #EndDate datetime;
set #n = 5;
set #StartDate = '20160830';
set #EndDate = dateadd(day, #n, #StartDate);
select cast(dateadd(day, number, #StartDate) as date) as MyDate,
cast(dateadd(day, number + 1, #StartDate) as date) as MyNextDate
from
(select distinct number from master.dbo.spt_values
where name is null
) n
where dateadd(day, number, #StartDate) < #EndDate;
Alternately you can use a temp table, table variable to store your dates, or a cte as well.
A recursive cte imlementation example is given below. Please note you would want to set MAXRECURSION option if you have a long date range as default for max recursion is 100.
declare #n int;
declare #StartDate datetime, #EndDate datetime;
set #n = 5;
set #StartDate = '20160830';
set #EndDate = dateadd(day, #n, #StartDate);
;with DateSeq as
(
select cast(#StartDate as date) as MyDate
union all
select dateadd(day , 1, MyDate) AS MyDate
from DateSeq where dateadd (day, 1, MyDate) < #EndDate
)
select MyDate, dateadd(day , 1, MyDate) AS NextDate
from DateSeq;
A temp table implementation example is as below.
declare #MyDateRange table(MyDate date);
Insert into #MyDateRange values('8/30/2016')
Insert into #MyDateRange values('9/1/2016')
Insert into #MyDateRange values('9/2/2016')
Insert into #MyDateRange values('9/3/2016')
Insert into #MyDateRange values('9/4/2016')
select MyDate, dateadd(day, 1, MyDate) as NextDate from #MyDateRange

Extract or Group by End of Year in SQL

Using this date range 02/03/2014 - 03/20/2016 how to generate this kind of result using sql
02/03/2014 - 12/31/2014
01/01/2015 - 12/31/2015
01/01/2016 - 03/20/2016
We can achieve this by building a recursive CTE.
Query
declare #startdate as date = '01/01/2014';
declare #enddate as date = '03/20/2016';
with dates as(
select dt = dateadd(yy, datediff(yy, 0, #startdate) + 1, -1)
where dateadd(yy, 1, #startDate) <= #endDate
union all
select dateadd(yy, 1, dt)
from dates
where dateadd(yy, 1, dt) <= #endDate
)
select cast(dt as date) as dt
from dates
union
select #enddate;
###Find a working demo here###
select max(date_column) MaxDateYearWise,datepart(YYYY,date_column) Year
into #dt
from date_range_table
group by datepart(YYYY,date_column)
select MaxDateYearWise from #dt
drop table #dt
--- Above query might give you the required result.

SQL Server : random date in specific range (including random hours, minutes,...)

I would like to create a random date for a SQL Server update query. I found a lot examples for random days or something similar but I couldn't find something which creates a random date with random date, hours, minutes, seconds AND milliseconds.
This is what I use to create the date randomly but it always gives me 00 as hour, minute, seconds and milliseconds and I don't know how I can randomize them as well.
This is my query:
declare #FromDate date = GETDATE()-2
declare #ToDate date = GETDATE()-1
UPDATE ACCOUNTS
SET dateFinished=
dateadd(day, rand(checksum(newid())) * (1 + datediff(day, #FromDate, #ToDate)), #FromDate)
This is how I'd do it:
Work out the number of seconds between from and to
Get a random number between zero and the number of seconds
Add that random number to the FromDate
Finally randomise the number of milliseconds
DECLARE #FromDate DATETIME = DATEADD(DAY, -2, GETDATE())
DECLARE #ToDate DATETIME = DATEADD(DAY, -1, GETDATE())
DECLARE #Seconds INT = DATEDIFF(SECOND, #FromDate, #ToDate)
DECLARE #Random INT = ROUND(((#Seconds-1) * RAND()), 0)
DECLARE #Milliseconds INT = ROUND((999 * RAND()), 0)
SELECT DATEADD(MILLISECOND, #Milliseconds, DATEADD(SECOND, #Random, #FromDate))
declare #FromDate dateTIME = '2014-01-01'
declare #ToDate dateTIME = '2014-12-31'
select top 100 dateadd(day,rand(checksum(newid()))*(1+datediff(day, #FromDate, #ToDate)), #FromDate) FROM Tabled(give your table name)
SELECT dateaddDATEADD(second,
second, (rand()*60+1),
DATEADD(minute,
(rand()*60+1) ,
DATEADD(day,
(rand()*365+1),
DATEADD(year,
-1,
getdate()))) )

I need to set the start date and end date into a variable in stored procedure

My requirement is set the #STARTDATE variable as 01[starting day]-month[current month]-year[current year] and based upon the month #ENDDATE changes in feb 28 days, jan 31 days
DECLARE #STARTDATE DATETIME
DECLARE #ENDDATE DATETIME
Based on month we divide the End date
DECLARE #MONTH int
SET #MONTH=(select MONTH(getdate()))
HERE I AM UNABLE TO DISPLAY THE DATE IN STARTDATE.
SET #STARTDATE = '01-+#MONTH+-+YEAR+'
IF (
#MONTH = 4
OR #MONTH = 6
)
SET #ENDDATE = '30-+#MONTH+-+YEAR+'
IF (#MONTH / 4 = 0)
SET #ENDDATE = '29-+#MONTH+-+YEAR+'
ELSE
SET #ENDDATE = '28-+#MONTH+-+YEAR+'
select #STARTDATE = dateadd(m, datediff(m, 0, current_timestamp), 0) startdate,
#ENDDATE = dateadd(m, datediff(m, 0, current_timestamp) + 1, -1) enddate
SQL Server 2012 introduced EMONTH() end of month function which returns the last date of the referenced month
Here is an example
SELECT EOMONTH(GETDATE())

Calculate 5 months before a date value

I have a query that outputs a date, and I'd like to add an additional column that represents the date 5 months prior to that date. So if the output value is 2012-06 then I want to show 2012-01.
SELECT
unnamed_date_column,
5_months_earlier = DATEADD(MONTH, -5, unnamed_date_column)
FROM dbo.unnamed_table;
If you are storing these as varchar (which you must be if they are in yyyy-mm, and you should stop doing that), then you can do this:
SELECT
unnamed_date_column,
5_months_earlier = DATEADD(MONTH, -5, unnamed_date_column)
FROM
(
SELECT unnamed_date_column = CONVERT(DATETIME, unnamed_varchar_column + '-01')
FROM dbo.unnamed_table
) AS x;
Of course, that could generate an error, because if you chose the wrong data type for this column, anybody could have entered 2013-13 or 1623-99 or who_dat into this column...
select [column]
from [table]
where [datecol] between DATEADD(month, -5, getdate()) and getdate()
After computing the start date of the first month (#Start) and the end date (#End) of the last month:
DECLARE #CurrentDate SMALLDATETIME; -- Or DATE[TIME][2][OFFSET]
SET #CurrentDate = GETDATE(); -- 2013-10-05
DECLARE #Start SMALLDATETIME, #End SMALLDATETIME;
SET #Start = DATEADD(MONTH, (DATEDIFF(MONTH, 0, #CurrentDate) - 4), 0);
SET #End = DATEADD(MONTH, (DATEDIFF(MONTH, 0, #CurrentDate) + 1), 0);
SELECT #Start AS [#Start], #End AS [#End];
/*
#Start #End
---------- ----------
2013-06-01 2013-11-01
*/
you could filter the rows using these predicates:
SELECT ...
FROM ...
WHERE SomeDateColumn >= #Start AND SomeDateColumn < #EndDate;
try this one:
DECLARE #DT DATETIME = GETUTCDATE()
SELECT CONVERT(VARCHAR(7),#DT, 120) AS TODAY_DATE, CONVERT(VARCHAR(7),DATEADD(MM,-5,#DT), 120 ) AS BEFORE_5_MONTHS

Resources