﻿<?xml version='1.0' encoding='UTF-8'?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>SQLServerCentral / SQL Server 2008 / SQL Server Newbies  / How to Calculate Total Monthly time worked / Latest Posts</title><generator>InstantForum.NET v2.9.0</generator><description>SQLServerCentral</description><link>http://www.sqlservercentral.com/Forums/</link><webMaster>notifications@sqlservercentral.com</webMaster><lastBuildDate>Sat, 18 May 2013 19:19:45 GMT</lastBuildDate><ttl>20</ttl><item><title>RE: How to Calculate Total Monthly time worked</title><link>http://www.sqlservercentral.com/Forums/Topic1032011-1292-1.aspx</link><description>Nice, and thanks for giving me an inferiority complex about my signature now... :) Seriously, though, you guys are the best. I'll refrain from offering forum advice for awhile, but hopefully will get to that point soonish.</description><pubDate>Fri, 10 Dec 2010 11:44:18 GMT</pubDate><dc:creator>autoexcrement</dc:creator></item><item><title>RE: How to Calculate Total Monthly time worked</title><link>http://www.sqlservercentral.com/Forums/Topic1032011-1292-1.aspx</link><description>[quote][b]Craig Farrell (12/10/2010)[/b][hr]Plenty of hope, I've been at this ten years or so, Wayne longer. Give yourself time.  Eventually you remember the functions offhand and then start coming up with strange and interesting ways to twist them together like burnt pretzels. :)[/quote]And, now that you understand what's going on here... you'll never forget it. So, you've been exposed to dateadd(datediff) to get the first of the month (change the datepart to get the first of any period!), and using reverse/stuff/reverse. Not too bad for one thread!EDIT: Check out the common date/time routines link in my signature!</description><pubDate>Fri, 10 Dec 2010 07:45:48 GMT</pubDate><dc:creator>WayneS</dc:creator></item><item><title>RE: How to Calculate Total Monthly time worked</title><link>http://www.sqlservercentral.com/Forums/Topic1032011-1292-1.aspx</link><description>[quote][b]autoexcrement (12/9/2010)[/b][hr]So, all that remains to be explained is...are you guys some kind of freaking sql wizards or what? [/quote] But of course! :w00t:[quote]What hope is there for us normal people with you lot lurking around? :)[/quote]Well, you see, that's the whole point. By lurking around, you are hopefully acquiring this knowledge transfer that's going on. Reinforce it by practice (aka, help out here on the forums). Don't get upset if what you come up with isn't "the best"; instead, learn from it. (If you look into the forums here, you'll find that most learning really goes on after the first answer was posted, with even well-versus folks learning from others. Even "the guru himself" (Jeff) recently learned a new safety check that can be applied to the infamous "quirky update" to guarantee things were processed correctly. (The learning never stops.....)</description><pubDate>Fri, 10 Dec 2010 07:40:28 GMT</pubDate><dc:creator>WayneS</dc:creator></item><item><title>RE: How to Calculate Total Monthly time worked</title><link>http://www.sqlservercentral.com/Forums/Topic1032011-1292-1.aspx</link><description>[quote][b]autoexcrement (12/9/2010)[/b][hr]Wayne, yes, thank you. That explains it completely. So, using your example of a time "80101", the code would (working from the inside out) transform it thusly:80101 (original)10108 (reversed)10:108 (stuff 3rd position with colon)10:10:8 (stuff 6th position with colon)8:01:01 (re-reverse)So, all that remains to be explained is...are you guys some kind of freaking sql wizards or what? What hope is there for us normal people with you lot lurking around? :)Thanks, I continue to be in awe at the creativity, intelligence, and amazing patience and tutelage available on this site.EDIT: P.S. Your double-stuffed remix is tasty too![/quote]One thing to note: The order that you do the STUFF calls can change what you're doing.Above, you inserted the colons from left to right. What this means is that you have to account for that colon in the subsequent calls to STUFF.The alternative is to insert them from right-to-left. Showing just them, it would be:1010:8 (stuff 5th position with colon)10:10:8 (stuff 3rd position with colon)You'll find a lot of folks will do it this way just to take that variable out of the way.</description><pubDate>Fri, 10 Dec 2010 07:34:58 GMT</pubDate><dc:creator>WayneS</dc:creator></item><item><title>RE: How to Calculate Total Monthly time worked</title><link>http://www.sqlservercentral.com/Forums/Topic1032011-1292-1.aspx</link><description>[quote][b]autoexcrement (12/9/2010)[/b][hr]Wayne, yes, thank you. That explains it completely. So, using your example of a time "80101", the code would (working from the inside out) transform it thusly:80101 (original)10108 (reversed)10:108 (stuff 3rd position with colon)10:10:8 (stuff 6th position with colon)8:01:01 (re-reverse)[/quote]On the money.[quote]So, all that remains to be explained is...are you guys some kind of freaking sql wizards or what? What hope is there for us normal people with you lot lurking around? :)Thanks, I continue to be in awe at the creativity, intelligence, and amazing patience and tutelage available on this site.[/quote]Plenty of hope, I've been at this ten years or so, Wayne longer. Give yourself time.  Eventually you remember the functions offhand and then start coming up with strange and interesting ways to twist them together like burnt pretzels. :)Oh, and thanks.Btw, regarding the brain?  Sorry, no can do.  After the amount of alcohol I've poisoned it with over the years I'm afraid it'll spontaneously combust if it is allowed an oxygen source.  ;-)</description><pubDate>Fri, 10 Dec 2010 02:08:43 GMT</pubDate><dc:creator>Evil Kraig F</dc:creator></item><item><title>RE: How to Calculate Total Monthly time worked</title><link>http://www.sqlservercentral.com/Forums/Topic1032011-1292-1.aspx</link><description>Wayne, yes, thank you. That explains it completely. So, using your example of a time "80101", the code would (working from the inside out) transform it thusly:80101 (original)10108 (reversed)10:108 (stuff 3rd position with colon)10:10:8 (stuff 6th position with colon)8:01:01 (re-reverse)So, all that remains to be explained is...are you guys some kind of freaking sql wizards or what? What hope is there for us normal people with you lot lurking around? :)Thanks, I continue to be in awe at the creativity, intelligence, and amazing patience and tutelage available on this site.EDIT: P.S. Your double-stuffed remix is tasty too!</description><pubDate>Thu, 09 Dec 2010 21:37:09 GMT</pubDate><dc:creator>autoexcrement</dc:creator></item><item><title>RE: How to Calculate Total Monthly time worked</title><link>http://www.sqlservercentral.com/Forums/Topic1032011-1292-1.aspx</link><description>[quote][b]autoexcrement (12/9/2010)[/b][hr]1. Craig, can I have an autographed photo of your brain for Chistmas?2. This is totally cool. I'm trying to figure it all out. I think I'm doing pretty well. Couple questions/confirmations (re: Post #1032106):[code="sql"]CONVERT( DateTime, CONVERT( VARCHAR(20), DateKey)) AS DateKey[/code]I guess this means you can't directly convert an INT to DateTime?[/quote]The answer to this is "it depends" - specifically on what you're storing in that int. If you are storing a date in YYYYMMDD format, then no. If you are storing an offset from 01/01/1900, then yes.[quote][code="sql"]DATEADD( mm, DATEDIFF( mm, 0, CONVERT( DATETIME, CONVERT( VARCHAR(20), DateKey))), 0) AS MonthStartDateKey[/code]Okay, this confuses me. I have taken it apart from the inside out, I understand what DATEADD and DATEDIFF do, but I don't understand the use of "0" here...?[/quote]If you were to run "SELECT CONVERT(DATETIME, 0)", you will see that this is converted to 01/01/1900.What the code is doing is getting the number of month boundaries crossed between 01/01/1900 and the other date. It then adds this number of months to 01/01/1900. The end result of this is that it will always return the first of the month for the specified date.[quote]And the [code="sql"]REVERSE, STUFF, REPEAT...[/code], as much as I'd like to pretend to understand it, I don't. If you feel like elaborating on any of this, I'd love to learn what exactly you're doing.[/quote]The REVERSE/STUFF/STUFF/REVERSE is taking the TimeKey field (time represented as an integer). Since leading zeros are not shown, anything before 10am will only be 5 digits instead of 6. So the intent is to add the colons between the hours/minutes and minutes/seconds. SELECT REVERSE('80101') will return 10108. We now can put those colons in the proper places. (STUFF adds the colon in the proper position.) Once finished, you have 10:10:8. You now need to reverse this again to have the valid time: 8:01:01.Edit: you could also do [code="sql"]STUFF(STUFF(RIGHT('0' + CONVERT(VARCHAR(6), TimeKey), 6),5,0,':'),3,0,':')[/code]. This converts the TimeKey to a string, prefixes it with a '0', takes the right 6 characters, and adds the colons.Does this explain it all?</description><pubDate>Thu, 09 Dec 2010 21:17:30 GMT</pubDate><dc:creator>WayneS</dc:creator></item><item><title>RE: How to Calculate Total Monthly time worked</title><link>http://www.sqlservercentral.com/Forums/Topic1032011-1292-1.aspx</link><description>1. Craig, can I have an autographed photo of your brain for Chistmas?2. This is totally cool. I'm trying to figure it all out. I think I'm doing pretty well. Couple questions/confirmations (re: Post #1032106):[code="sql"]CONVERT( DateTime, CONVERT( VARCHAR(20), DateKey)) AS DateKey[/code]I guess this means you can't directly convert an INT to DateTime?[code="sql"]DATEADD( mm, DATEDIFF( mm, 0, CONVERT( DATETIME, CONVERT( VARCHAR(20), DateKey))), 0) AS MonthStartDateKey[/code]Okay, this confuses me. I have taken it apart from the inside out, I understand what DATEADD and DATEDIFF do, but I don't understand the use of "0" here...?And the [code="sql"]REVERSE, STUFF, REPEAT...[/code], as much as I'd like to pretend to understand it, I don't. If you feel like elaborating on any of this, I'd love to learn what exactly you're doing.</description><pubDate>Thu, 09 Dec 2010 20:24:34 GMT</pubDate><dc:creator>autoexcrement</dc:creator></item><item><title>RE: How to Calculate Total Monthly time worked</title><link>http://www.sqlservercentral.com/Forums/Topic1032011-1292-1.aspx</link><description>[quote][b]KS-321165 (12/8/2010)[/b][hr]Thank You! You saved me a ton of time.[/quote]You're welcome.  If there's any bits and pieces of that you don't understand come back and ask.  You're going to have to maintain that, so you really need to understand all the things I did against your dates and times to make them work.</description><pubDate>Wed, 08 Dec 2010 14:34:02 GMT</pubDate><dc:creator>Evil Kraig F</dc:creator></item><item><title>RE: How to Calculate Total Monthly time worked</title><link>http://www.sqlservercentral.com/Forums/Topic1032011-1292-1.aspx</link><description>Thank You! You saved me a ton of time.</description><pubDate>Wed, 08 Dec 2010 14:29:46 GMT</pubDate><dc:creator>KS-321165</dc:creator></item><item><title>RE: How to Calculate Total Monthly time worked</title><link>http://www.sqlservercentral.com/Forums/Topic1032011-1292-1.aspx</link><description>[quote][b]KS-321165 (12/8/2010)[/b][hr]Thanks. I am learning CTE and so it was helpful when you broke it down, but how do you put all this in one query?:-)[/quote][code="sql"]SELECT	drvStart.ResourceID,	DATEADD( mm, DATEDIFF( mm, 0, drvStart.DateKey), 0) AS MonthStartDateKey,	SUM( DATEDIFF(n, StartTime, ISNULL( EndTime, CONVERT( DATETIME, '1/1/1900 23:59:59')))) AS TotalMinutesWorkedInMonthFROM		(SELECT        ResourceID,        CONVERT( DateTime, CONVERT( VARCHAR(20), DateKey)) AS DateKey,        MIN( Convert( Datetime, '1/1/1900 ' + REVERSE( STUFF( STUFF( REVERSE( CONVERT( VARCHAR(30), TimeKey)), 3, 0, ':'), 6, 0, ':')))) AS StartTime	FROM			#Astime	WHERE			EventType = 2	GROUP BY			ResourceID,			DateKey	) AS drvStart	LEFT JOIN		(SELECT			ResourceID,			CONVERT( DateTime, CONVERT( VARCHAR(20), DateKey)) AS DateKey,			MAX( Convert( Datetime, '1/1/1900 ' + REVERSE( STUFF( STUFF( REVERSE( CONVERT( VARCHAR(30), TimeKey)), 3, 0, ':'), 6, 0, ':')))) AS EndTime		FROM				#Astime		WHERE				EventType = 3		GROUP BY				ResourceID,				DateKey		) AS drvEnd	ON	drvStart.ResourceID = drvEnd.ResourceID		AND drvStart.DateKey = drvEnd.DateKeyGROUP BY	drvStart.ResourceID,	DATEADD( mm, DATEDIFF( mm, 0, drvStart.DateKey), 0)[/code]</description><pubDate>Wed, 08 Dec 2010 14:24:01 GMT</pubDate><dc:creator>Evil Kraig F</dc:creator></item><item><title>RE: How to Calculate Total Monthly time worked</title><link>http://www.sqlservercentral.com/Forums/Topic1032011-1292-1.aspx</link><description>Thanks. I am learning CTE and so it was helpful when you broke it down, but how do you put all this in one query?:-)</description><pubDate>Wed, 08 Dec 2010 13:01:51 GMT</pubDate><dc:creator>KS-321165</dc:creator></item><item><title>RE: How to Calculate Total Monthly time worked</title><link>http://www.sqlservercentral.com/Forums/Topic1032011-1292-1.aspx</link><description>I broke this into CTE's because it's easier to see the methodology that way.  You could do this all in one query if you wanted.  The key is the two subqueries, which are listed as cte and cte2.Note one of the larger issues is turning your separate date and time stamps into usable values.[code="sql"]/*if (object_id('tempdb..#Astime') is not null) drop table #Astimecreate table #Astime (ResourceId smallint, Site smallint,DateKey int, TimeKey int, EventType smallint)	insert into #Astimeselect 1, 1, 20100901, 80010,2union select 1, 1, 20100901, 113001,3 union select 1, 1, 20100901, 122014,2union select 1, 1, 20100901, 153223,3union select 1, 1, 20100901, 153814,2union select 1, 1, 20100901, 161503,3union select 1, 1, 20100902, 80010,2union select 1, 1, 20100902, 122014,2union select 1, 1, 20100902, 153223,3union select 1, 1, 20100902, 153814,2union select 1, 1, 20100902, 161510,3unionselect 2, 1, 20100901, 80015,2union select 2, 1, 20100901, 113001,3 union select 2, 1, 20100901, 122014,2union select 2, 1, 20100901, 153223,3union select 2, 1, 20100901, 153814,2union select 2, 1, 20100901, 161523,3union select 2, 1, 20100902, 80010,2union select 2, 1, 20100902, 122014,2union select 2, 1, 20100902, 153223,3union select 2, 1, 20100902, 153814,2union select 2, 1, 20100902, 161520,3*/;WITH cte AS(SELECT	ResourceID,	DateKey,	MIN( TimeKey) AS StartTimeFROM	#AstimeWHERE	EventType = 2GROUP BY	ResourceID,	DateKey),cte2 AS(SELECT	ResourceID,	DateKey,	MAX( TimeKey) AS EndTimeFROM	#AstimeWHERE	EventType = 3GROUP BY	ResourceID,	DateKey)	,cte3 AS(SELECT	c.ResourceID,	c.DateKey,	c.StartTime,	ISNULL( c2.EndTime, 115959) AS EndTimeFROM	cte AS c	LEFT JOIN		cte2 AS c2	On	c.ResourceID = c2.ResourceID		AND c.DateKey = c2.DateKey), cte4 AS(SELECT 	ResourceID,	CONVERT( DateTime, CONVERT( VARCHAR(20), DateKey)) AS DateKey,	DATEADD( mm, DATEDIFF( mm, 0, CONVERT( DATETIME, CONVERT( VARCHAR(20), DateKey))), 0) AS MonthStartDateKey,	--REVERSE( STUFF( STUFF( REVERSE( CONVERT( VARCHAR(30), StartTime)), 3, 0, ':'), 6, 0, ':')) AS test	Convert( Datetime, '1/1/1900 ' + REVERSE( STUFF( STUFF( REVERSE( CONVERT( VARCHAR(30), StartTime)), 3, 0, ':'), 6, 0, ':'))) AS StartTime,	Convert( Datetime, '1/1/1900 ' + REVERSE( STUFF( STUFF( REVERSE( CONVERT( VARCHAR(30), endTime)), 3, 0, ':'), 6, 0, ':'))) AS EndTimeFROM	cte3)SELECT	ResourceID,	MonthStartDateKey,	SUM( DATEDIFF(n, StartTime, EndTime)) AS TotalMinutesWorkedInMonthFROM	cte4GROUP BY	ResourceID,	MonthStartDateKey[/code]</description><pubDate>Wed, 08 Dec 2010 12:18:46 GMT</pubDate><dc:creator>Evil Kraig F</dc:creator></item><item><title>RE: How to Calculate Total Monthly time worked</title><link>http://www.sqlservercentral.com/Forums/Topic1032011-1292-1.aspx</link><description>:-)Thanks. Here it is:if (object_id('tempdb..#Astime') is not null) drop table #Astimecreate table #Astime (ResourceId smallint, Site smallint, DateKey int, TimeKey int, EventType smallint)insert into #Astimeselect 1, 1, 20100901, 80010,2union select 1, 1, 20100901, 113001,3 union select 1, 1, 20100901, 122014,2union select 1, 1, 20100901, 153223,3union select 1, 1, 20100901, 153814,2union select 1, 1, 20100901, 161503,3union select 1, 1, 20100902, 80010,2union select 1, 1, 20100902, 122014,2union select 1, 1, 20100902, 153223,3union select 1, 1, 20100902, 153814,2union select 1, 1, 20100902, 161510,3unionselect 2, 1, 20100901, 80015,2union select 2, 1, 20100901, 113001,3 union select 2, 1, 20100901, 122014,2union select 2, 1, 20100901, 153223,3union select 2, 1, 20100901, 153814,2union select 2, 1, 20100901, 161523,3union select 2, 1, 20100902, 80010,2union select 2, 1, 20100902, 122014,2union select 2, 1, 20100902, 153223,3union select 2, 1, 20100902, 153814,2union select 2, 1, 20100902, 161520,3select * from #Astime</description><pubDate>Wed, 08 Dec 2010 11:40:10 GMT</pubDate><dc:creator>KS-321165</dc:creator></item><item><title>RE: How to Calculate Total Monthly time worked</title><link>http://www.sqlservercentral.com/Forums/Topic1032011-1292-1.aspx</link><description>Any chance you can post the sample data and DDL like in the first link of my sig?  Will make life much easier.</description><pubDate>Wed, 08 Dec 2010 11:12:29 GMT</pubDate><dc:creator>Evil Kraig F</dc:creator></item><item><title>How to Calculate Total Monthly time worked</title><link>http://www.sqlservercentral.com/Forums/Topic1032011-1292-1.aspx</link><description>I need to work out the total monthly time an emplyee is working given the signon and signoff times. All I need to use is the time the employee first signed on in the morning and the last time the employee signedoff. I don't need the time inbetween.Table is:  ResourceID (int), Site (int), DateKey(yyyymmdd), TimeKey(hh:mm:ss), EventType(int).Event type of 2 indicates signon ,3 signoff  and 4 idleThis is the sample data:ResourceId   Site   DateKey       TimeKey  EventType  1               1       20100901    80010            2  1               1       20100901    113001          3  1               1       20100901    122014          2  1               1       20100901    153223          3  1               1       20100901    153814          2  1               1       20100901    161503          3  1               1       20100902    80010            2  1               1       20100902    113001          3  1               1       20100902    122014          2  1               1       20100902    153223          3  1               1       20100902    153814          2  1               1       20100902    161503          3  2               1       20100901    80010            2  2               1       20100901    113001          3  2               1       20100901    122014          2  2               1       20100901    153223          3  2               1       20100901    153814          2  2               1       20100901    161503          3  2               1       20100902    80010            2  2               1       20100902    113001          3  2               1       20100902    122014          2  2               1       20100902    153223          3  2               1       20100902    153814          2  2               1       20100902    161503          3Is there a simpler way to do this without using temporary tables?Thanks</description><pubDate>Wed, 08 Dec 2010 10:12:32 GMT</pubDate><dc:creator>KS-321165</dc:creator></item></channel></rss>