Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Create Pivot Table (crosstab) in SQL 2008

Posted on 2009-07-02
7
Medium Priority
?
1,110 Views
Last Modified: 2012-05-07
I have a table    WeekTaskStatus  with Task WeekEnd and TaskStatus
Task      WeekEnd      TaskStatus
Budget      4/24/2009      Green
Resources      4/24/2009      Yellow
Scope      4/24/2009      Red
Timeline      4/24/2009      Yellow
Budget      5/1/2009      Yellow
Resources      5/1/2009      Green
Scope      5/1/2009      Red
Timeline      5/1/2009      Yellow
Budget      5/8/2009      Green
Resources      5/8/2009      Red
Scope      5/8/2009      Yellow
Timeline      5/8/2009      Green
Budget      5/15/2009      Green
Resources      5/15/2009      Yellow
Scope      5/15/2009      Red
Timeline      5/15/2009      Yellow
Budget      5/22/2009      Yellow
Resources      5/22/2009      Red
Scope      5/22/2009      Red
Timeline      5/22/2009      Yellow

I am trying to create an SQL pivot to display the data as shown below
      Budget      Resources      Scope      Timeline
4/24/2009      Green      Yellow      Red      Yellow
5/1/2009      Yellow      Green      Red      Yellow
5/8/2009      Green      Red      Yellow      Green
5/15/2009      Green      Yellow      Red      Yellow
5/22/2009      Yellow      Red      Red      Yellow

The number of Tasks will increase, so the pivot needs to account for the future additional columns.
There will only be one TaskStatus per WeekEnding per Task.
Is this possible?
0
Comment
Question by:Scamquist
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
7 Comments
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 24766981
You can look at the PIVOT keyword for SQL keeping in mind that it  requires hard coding of column names (values) to be pivoted.

Here is a nice article by Tim Chapman on the subject:
http://articles.techrepublic.com.com/5100-10878_11-6143761.html

Here is a solution from Mark Wills here on EE:
http://www.experts-exchange.com/articles/Microsoft/Development/MS-SQL-Server/SQL-Server-2005/Dynamic-Pivot-Procedure-for-SQL-Server.html
0
 
LVL 1

Author Comment

by:Scamquist
ID: 24767030
Once the solution is in place, we may add additional tasks.  I would be too cumbersome ot go back and hard code new column names.

I have been looking for awhile and have seen references to having the column created dynamically.  
0
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 24767054
Yes, using dynamic SQL.  Take a look at the second link I posted from Mark talking about that.  His article is providing a nice dynamic SQL procedure which will do this for you OR you can at least learn to build a similar implementation.
0
Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

 
LVL 41

Accepted Solution

by:
ralmada earned 1400 total points
ID: 24767469
I agree with mwvisa1, dynamic SQL is the way to go here. I have customized the alternative I always use based on the sample table provided. Have a look:
Declare @strSQL varchar(max)
DECLARE @cols varchar(2000)
 
SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
                                '],[' + task
                        FROM    WeekTaskStatus
                        ORDER BY '],[' + task
                        FOR XML PATH('')
                      ), 1, 2, '') + ']'
 
 
set @strSQL = 'select WeekEnd, ' + @cols +
		' from (
			select WeekEnd, Task, TaskStatus from WeekTaskStatus) o
		  pivot (Max(Task) for Task in (' + @cols + ')) p'
 
exec(@strSQL)

Open in new window

0
 
LVL 1

Author Comment

by:Scamquist
ID: 24767613
I think we are almost there,

The code you provided returned the column header in the body.  
I changed line 15 to
pivot (Max(TaskStatus) for Task in (' + @cols + ')) p'

which inserted the Red, Yellow or Green in the body :)  

However, I get and Error Box:
Error - SQL Syntax Errors Encountered
The following errors were encountered while parsing the contenst of the SQL pane.
The Declare SQL construct or statement is not supported.

If I ignore, the query runs, but I can't save it.

Ideas?
0
 
LVL 60

Assisted Solution

by:Kevin Cross
Kevin Cross earned 600 total points
ID: 24767645
Are you trying to save this in a view, if so that will not work.  You will have to save it in a stored procedure or table based user defined function.
0
 
LVL 1

Author Closing Comment

by:Scamquist
ID: 31599331
Thank you both.  I have been burning up the internet trying to find the answer.  The only answers I found used many dozens of lines of code.  Very complicated.  Thank you so much
0

Featured Post

Use Case: Protecting a Hybrid Cloud Infrastructure

Microsoft Azure is rapidly becoming the norm in dynamic IT environments. This document describes the challenges that organizations face when protecting data in a hybrid cloud IT environment and presents a use case to demonstrate how Acronis Backup protects all data.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Microsoft Access is a place to store data within tables and represent this stored data using multiple database objects such as in form of macros, forms, reports, etc. After a MS Access database is created there is need to improve the performance and…
Recently I was talking with Tim Sharp, one of my colleagues from our Technical Account Manager team about MongoDB’s scalability. While doing some quick training with some of the Percona team, Tim brought something to my attention...
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

688 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question