Question

Pivot the data into weeks

Asked by: seazodiac

Data sample in original format:
key           date_worked                             hours
11      2005-01-04 00:00:00.000      8.00
11      2005-01-05 00:00:00.000      8.00
11      2005-01-06 00:00:00.000      8.00
11      2005-01-07 00:00:00.000      8.00
11      2005-01-03 00:00:00.000      8.00
11      2005-01-17 00:00:00.000      8.00
11      2005-01-18 00:00:00.000      8.00
11      2005-01-19 00:00:00.000      8.00
11      2005-01-20 00:00:00.000      8.00
11      2005-01-21 00:00:00.000      8.00
11      2005-01-24 00:00:00.000      4.00
11      2005-01-25 00:00:00.000      8.00
11      2005-01-26 00:00:00.000      8.00




Need to transform into this:


key           week 1                        week 2                                   week 3            week 4
11            total_hours in week 1   total in week2                       total in week3      total in week 4




keep in mind while ironing out a solution:
1.  I simplified the example so it only has one key value, there might other values for the key 11, 23, 12, 34, etc, so it has to be grouped by key

2. the week count is from the first day of the current year (ignore any week prior to this year) up until the current date (which is getdate() value).


500pts goes to the early birds.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2005-02-01 at 12:11:18ID21297449
Tags

pivot

Topic

MS SQL Server

Participating Experts
1
Points
500
Comments
12

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Transform - Pivot statement
    TRANSFORM Sum(Table1.Value) AS SumOfValue SELECT Table1.Year FROM Table1 GROUP BY Table1.Year PIVOT Table1.DestCountry; This works like I want to. The problem is, Table1.DestCountry is a number. In another table, I have the information I need to replace the number with th...
  2. Pivot/transform and Union
    I have a problem with pivot/transform work with union, here is the sql statement: transform sum([sales amount]) as amount select class from table1 group by class pivot year <----(part A) union transform sum([sales amount]) as amount select class from table2 group by...
  3. Using GetDate() in SSIS with Derived transformation
    Guys: I’m trying to add a new column using the Derived Column transformation; I need to accomplish the following but not having any luck: Need to substract 1 ½ day from Current time. This is what I have: GETDATE() – 1.5 This is not working, I know I have to use a cast op...
  4. Access Transform\Pivot
    I am using access and wanted to know if there can be more then 1 field list in a transform function. Meaning transform sum(field1) as field1sum, ANOTHER VALUE select ...... pivot ....... Or can you only have this transform sum(field1) as field1sum select ...... pivot .......

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: ScottPletcherPosted on 2005-02-01 at 12:28:23ID: 13196858

DECLARE @weeks TABLE (weekNum TINYINT, weekStart SMALLDATETIME, weekEnd SMALLDATETIME)
DECLARE @weekNum TINYINT
DECLARE @weekStart SMALLDATETIME
DECLARE @weekEnd SMALLDATETIME
SET @weekNum = 1
SET @weekStart = '2005-01-01'
SET @weekEnd = DATEADD(MINUTE, -1, DATEADD(DAY, 7, @weekStart))

WHILE @weakStart <= GETDATE()
BEGIN
      INSERT INTO @weeks VALUES(@weekNum, @weekStart, @weekEnd)
      SET @weekNum = @weekNum + 1
      SET @weekStart = DATEADD(DAY, 7, @weekStart)
      SET @weekEnd = DATEADD(DAY, 7, @weekEnd)
END --WHILE

SELECT key,
      SUM(CASE WHEN weekNum = 1 THEN hours ELSE 0 END) AS [Week 1],
      SUM(CASE WHEN weekNum = 2 THEN hours ELSE 0 END) AS [Week 2],
      SUM(CASE WHEN weekNum = 3 THEN hours ELSE 0 END) AS [Week 3],
      SUM(CASE WHEN weekNum = 4 THEN hours ELSE 0 END) AS [Week 4]
FROM data
INNER JOIN @weeks ON data.date_worked BETWEEN weekStart AND weekEnd
GROUP BY key

 

by: ScottPletcherPosted on 2005-02-01 at 12:30:21ID: 13196884

You could create a permanent table with the weeks in it, and then just use the final query.

If you have a lot of data in the table, and an index on date_worked, and you will only process some of the rows from the data table, it would probably be worthwhile to add a WHERE clause to check date_worked for the range of dates to be processed.  Let me know if that applies here.

 

by: seazodiacPosted on 2005-02-01 at 12:31:33ID: 13196897

If possible at all, I don't want to create temp table.

 

by: ScottPletcherPosted on 2005-02-01 at 12:38:24ID: 13196969

CORRECTIONS:
*) typo, misspelled "week" as "weak" on the WHILE
*) I used SMALLDATETIME instead of DATETIME
*) I hard-coded "2005" instead of using the current year


DECLARE @weeks TABLE (weekNum TINYINT, weekStart DATETIME, weekEnd DATETIME)
DECLARE @weekNum TINYINT
DECLARE @weekStart DATETIME
DECLARE @weekEnd DATETIME
SET @weekNum = 1
-- set first week start datetime to Jan 1 of current year
SET @weekStart = STUFF(CONVERT(CHAR(8), GETDATE(), 112), 5, 4, '0101')
SET @weekEnd = DATEADD(MILLISECOND, -3, DATEADD(DAY, 7, @weekStart))

SET NOCOUNT ON
WHILE @weekStart <= GETDATE()
BEGIN
      INSERT INTO @weeks VALUES(@weekNum, @weekStart, @weekEnd)
      SET @weekNum = @weekNum + 1
      SET @weekStart = DATEADD(DAY, 7, @weekStart)
      SET @weekEnd = DATEADD(DAY, 7, @weekEnd)
END --WHILE
SET NOCOUNT OFF

--SELECT * FROM @weeks

SELECT [key],
      SUM(CASE WHEN weekNum = 1 THEN hours ELSE 0 END) AS [Week 1],
      SUM(CASE WHEN weekNum = 2 THEN hours ELSE 0 END) AS [Week 2],
      SUM(CASE WHEN weekNum = 3 THEN hours ELSE 0 END) AS [Week 3],
      SUM(CASE WHEN weekNum = 4 THEN hours ELSE 0 END) AS [Week 4]
FROM data
INNER JOIN @weeks ON data.date_worked BETWEEN weekStart AND weekEnd
GROUP BY [key]

 

by: ScottPletcherPosted on 2005-02-01 at 12:40:13ID: 13196987

>> If possible at all, I don't want to create temp table. <<

I understand.  But SQL is actually more efficient joining to that table than using another method.  Also, the table will never be more than 53 rows, so it will always fit in one data page.  

Finally, you could create a permanent table with the current year's weeks already in it and just issue the final SELECT shown.

 

by: seazodiacPosted on 2005-02-01 at 12:42:48ID: 13197010

>>>>But SQL is actually more efficient joining to that table than using another method.  

sounds persuasive.  true.

but this section of query:

SELECT [key],
     SUM(CASE WHEN weekNum = 1 THEN hours ELSE 0 END) AS [Week 1],
     SUM(CASE WHEN weekNum = 2 THEN hours ELSE 0 END) AS [Week 2],
     SUM(CASE WHEN weekNum = 3 THEN hours ELSE 0 END) AS [Week 3],
     SUM(CASE WHEN weekNum = 4 THEN hours ELSE 0 END) AS [Week 4]
FROM data
INNER JOIN @weeks ON data.date_worked BETWEEN weekStart AND weekEnd
GROUP BY [key]



Do I have to hardcoded weeknum=1, 2, 3, 4? Shouldn't that be dynamic? I.e., what if you have 5 weeks between the dates?

 

by: ScottPletcherPosted on 2005-02-01 at 12:50:07ID: 13197080

Ah, yes, good point, but you will need to specify at least the starting weekNum / date and, if you want to report on a variable number of weeks, then ending date as well.

Note that there is no way to change the column headings without using dynamic SQL.  So "Week 1" will be the first week *reported* on, "Week 2" will be the second week *reported*, and so on.

For the simplest case, specify starting week (default = 1) and have a fixed 4 weeks reported:

DECLARE @startWeekNum TINYINT
SET @startWeekNum = 3  --<<-- of course could be input param in sp with def. = 1

...other declares...
...build date table, loading only needed week(s) based on @startWeekNum...

SELECT [key],
     SUM(CASE WHEN weekNum = @startWeekNum THEN hours ELSE 0 END) AS [Week 1],
     SUM(CASE WHEN weekNum = @startWeekNum + 1 THEN hours ELSE 0 END) AS [Week 2],
     SUM(CASE WHEN weekNum = @startWeekNum + 2 THEN hours ELSE 0 END) AS [Week 3],
     SUM(CASE WHEN weekNum = @startWeekNum + 3 THEN hours ELSE 0 END) AS [Week 4]
FROM data
INNER JOIN @weeks ON data.date_worked BETWEEN weekStart AND weekEnd
GROUP BY [key]

 

by: ScottPletcherPosted on 2005-02-01 at 12:51:45ID: 13197098

I don't normally recommend using dynamic SQL, but it would also allow you to avoid a temp/perm table in this particular case and have custom column headings.  As long as you understand and can accept the security implications, it's a good choice here.  Give me a few minutes and I'll post a sample.

 

by: seazodiacPosted on 2005-02-01 at 13:00:18ID: 13197194

Scott, I think you are pretty close to the solution.

Another wrinkle here, is that given two dates, starting date, and ending date, how do you dynamically break the days in between into weeks, and generate a report columnized by week number on the fly?

an example is due here;

say January 1, 2005 to January 31, 2005 is the input of this store procedure.

I want stored procedure to generate report of total hours by week number horizontally by user provided two dates.
Hope I made this clear enough for you to work

 

by: ScottPletcherPosted on 2005-02-01 at 13:24:12ID: 13197461

OK, look at the results of this; if you like it, comment the PRINT @sql and uncomment the EXEC(@sql) and this should be a good start.  
You should add some date checks/verifications (start date is actual start of week, or adjust it to one; end date is actual end of week, or adjust it one; start date is < current date; etc.); if you want some code for that as well, let me know.
You could make other enhancements as well.  For example, allow a specific key to be passed in; if so, report on that key only, else report on all keys.


Sample invocations:

EXEC workHoursByKey
EXEC workHoursByKey '2005-01-08', '2005-03-15'


CREATE PROCEDURE WorkHoursByKey
      @startDate DATETIME = NULL,  --default = Jan 1 of current year
      @endDate DATETIME = NULL    --default = four wks listed
AS
IF @startDate IS NULL
      SET @startDate = STUFF(CONVERT(CHAR(8), GETDATE(), 112), 5, 4, '0101')
IF @endDate IS NULL
      SET @endDate = DATEADD(MILLISECOND, -3, DATEADD(DAY, 28, @startDate))

DECLARE @workDate DATETIME
DECLARE @sql VARCHAR(3000)

SET @workDate = @startDate

SET @sql = 'SELECT [key], ' + CHAR(13)

WHILE @workDate < @endDate
BEGIN
      SET @sql = @sql + '    SUM(CASE WHEN date_worked BETWEEN ''' +
            CONVERT(VARCHAR(30), @workDate, 121) + ''' AND ''' +
            CONVERT(VARCHAR(30), DATEADD(MS, -3, DATEADD(DAY, 7, @workDate)), 121) +
            ''' THEN hours ELSE 0 END) AS [Week of ' +
            CONVERT(CHAR(5), @workDate, 1) + '],' + CHAR(13)
      SET @workDate = DATEADD(DAY, 7, @workDate)
END --WHILE

-- remove trailing comma, then complete building query
SET @sql = STUFF(@sql, LEN(@sql) - 1, 2, '') + CHAR(13) +
      'FROM data ' + CHAR(13) +
      'WHERE date_worked BETWEEN ''' + CONVERT(VARCHAR(30), @startDate, 121) +
      ''' AND ''' + CONVERT(VARCHAR(30), @endDate, 121) + '''' + CHAR(13) +
      'GROUP BY [key] '

PRINT @sql
--EXEC(@sql)
GO

 

by: ScottPletcherPosted on 2005-02-01 at 13:50:21ID: 13197758

You should consider pre-building a table with work weeks in it, something like:

CREATE TABLE workWeeks (
    weekNum SMALLINT NOT NULL,
    startDate DATETIME NOT NULL,
    endDate DATETIME NOT NULL
)

The table can be pre-loaded once at the start of the year and you avoid all future calcs to determine week num (you could load up to 5 yrs' worth of data and it would still fit in a single data page).  You just join to the table to determine the week num and/or adjust to the startDate of that week.

 

by: seazodiacPosted on 2005-02-18 at 05:23:33ID: 13345187

The creation of this lookup table seems properly necessary. and its existence makes this whole thing much easier.
thanks

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...