Solved

how can i pivot this resultset?

Posted on 2010-08-26
6
246 Views
Last Modified: 2012-05-10
so i have the sql below
 
SELECT top 10 sc.CodeName, rs.EndDate, t1.EndDate
FROM ReleaseSchedule rs
INNER JOIN StatusCode sc
ON rs.MilestoneCID = sc.CID
LEFT OUTER JOIN
   (SELECT pm.MilestoneCID, pm.EndDate
   FROM ProjectMilestone pm
   INNER JOIN StatusCode sc
   ON pm.MilestoneCID = sc.CID) as t1
ON rs.MilestoneCID = t1.MilestoneCID

WHERE rs.EndDate >= GetDate()
ORDER BY rs.EndDate

Open in new window


it generates the following result set:

milestone                                                 MreleaseDate                            MprojectDate
Functional Certification                                2010-08-31 00:00:00.000      NULL
QA Certification / UA Complete               2010-09-30 00:00:00.000      NULL
Code Freeze                                             2010-10-15 00:00:00.000      NULL

how can i pivot this result so that i get milestones as the fields with the two dates under each milestone?

thanks all the SQL gurus out there.
Dark Pod Build Start                                    2010-10-31 00:00:00.000      NULL
0
Comment
Question by:realcoding
[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
  • 2
6 Comments
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 33537552
See if this helps (see code snippet).

Explanation:
+Wrap your above query in a common table expression (can save to a view if will reuse. Note replaced the ORDER BY and TOP syntax with ROW_NUMBER().
+Using the CTE, we join to subqueries using UNION so that our date values are under one column.
+Use PIVOT keyword for SQL 2005 to pivot based on the Milestone. If these are not static and finite in nature (i.e., you need to list however many there are and whatever names they are, then you will need to turn to Dynamic SQL -- Mark Will's has a nice article here on that, so advise if that is the approach you need and can provide a link).

Best regards,

Kevin
;WITH milestonesCTE(Milestone, MreleaseDate, MprojectDate)
AS
(
SELECT sc.CodeName, rs.EndDate, t1.EndDate
     , ROW_NUMBER() OVER(ORDER BY rs.EndDate) rn
FROM ReleaseSchedule rs
INNER JOIN StatusCode sc
ON rs.MilestoneCID = sc.CID
LEFT OUTER JOIN(
   SELECT pm.MilestoneCID, pm.EndDate
   FROM ProjectMilestone pm
   INNER JOIN StatusCode sc
   ON pm.MilestoneCID = sc.CID
) as t1 ON rs.MilestoneCID = t1.MilestoneCID
WHERE rs.EndDate >= GetDate()
)
SELECT *
FROM (
   SELECT Milestone
        , MreleaseDate AS DateValue
        , 'Mrelease' AS DateType
   FROM milestonesCTE
   WHERE rn <= 10
   UNION ALL
   SELECT Milestone
        , MprojectDate AS DateValue
        , 'Mproject' AS DateType
   FROM milestonesCTE
   WHERE rn <= 10
) upvt
PIVOT (
   MAX(DateValue)
   FOR Milestone
   IN ([Functional Certification], 
       [QA Certification / UA Complete], 
       [Code Freeze])
) pvt
;

Open in new window

0
 
LVL 58

Expert Comment

by:cyberkiwi
ID: 33538570
No points for me, the first line should be

;WITH milestonesCTE(Milestone, MreleaseDate, MprojectDate, RN)

Great solution by Kevin, and useful pointers as well.
SQL Server has come a long way to be able to optimize the row_number() function into a similar plan to TOP.  I would still keep the ORDER BY and TOP, if for nothing else, then for fear SQL Server throws an incorrect plan every now and then.

The following is one of some test iterations I did and it consistently performs slightly better with TOP present in the query.
create table ReleaseSchedule(MilestoneID int primary key, MilestoneCID int, EndDate datetime)
create index ix_ReleaseSchedule on ReleaseSchedule(MilestoneCID)
create table StatusCode(CID int primary key, CodeName varchar(50))
create table ProjectMilestone(PMID int primary key, MilestoneCID int, EndDate datetime)
create index ix_ProjectMilestone on ProjectMilestone(MilestoneCID)

delete StatusCode delete ReleaseSchedule delete ProjectMilestone
insert StatusCode select 1, 'Functional Certification'
insert StatusCode select 2, 'QA Certification / UA Complete'
insert StatusCode select 3, 'Code Freeze'
insert ReleaseSchedule select 10, 1, '2010-08-31'
insert ReleaseSchedule select 11, 2, '2010-09-30'
insert ReleaseSchedule select 12, 3, '2010-10-15'
insert ReleaseSchedule select MilestoneID+10, MilestoneCID, EndDate+1 from ReleaseSchedule
insert ReleaseSchedule select MilestoneID+20, MilestoneCID, EndDate+2 from ReleaseSchedule
insert ReleaseSchedule select MilestoneID+40, MilestoneCID, EndDate+3 from ReleaseSchedule
insert ReleaseSchedule select MilestoneID+80, MilestoneCID, EndDate+4 from ReleaseSchedule
insert ReleaseSchedule select MilestoneID+160, MilestoneCID, EndDate+5 from ReleaseSchedule
insert StatusCode select CID+10, CodeName+'a' from StatusCode
insert StatusCode select CID+20, CodeName+'b' from StatusCode
insert StatusCode select CID+40, CodeName+'c' from StatusCode
insert StatusCode select CID+80, CodeName+'d' from StatusCode
update ReleaseSchedule set MileStoneCID=MilestoneID-9
insert ProjectMilestone select 1000+MilestoneID, MilestoneCID, EndDate+cast(Rand()*10 as int) from ReleaseSchedule

SELECT top 10 sc.CodeName, rs.EndDate, t1.EndDate
FROM ReleaseSchedule rs
INNER JOIN StatusCode sc
ON rs.MilestoneCID = sc.CID
LEFT OUTER JOIN
   (SELECT pm.MilestoneCID, pm.EndDate
   FROM ProjectMilestone pm
   INNER JOIN StatusCode sc
   ON pm.MilestoneCID = sc.CID) as t1
ON rs.MilestoneCID = t1.MilestoneCID
WHERE rs.EndDate >= GetDate()
ORDER BY rs.EndDate


;WITH milestonesCTE(Milestone, MreleaseDate, MprojectDate,rn)
AS
(
SELECT top 7 sc.CodeName, rs.EndDate, t1.EndDate
     , ROW_NUMBER() OVER(ORDER BY rs.EndDate) rn
FROM ReleaseSchedule rs
INNER JOIN StatusCode sc
ON rs.MilestoneCID = sc.CID
LEFT OUTER JOIN(
   SELECT pm.MilestoneCID, pm.EndDate
   FROM ProjectMilestone pm
   INNER JOIN StatusCode sc
   ON pm.MilestoneCID = sc.CID
) as t1 ON rs.MilestoneCID = t1.MilestoneCID
WHERE rs.EndDate >= GetDate()
ORDER BY rs.EndDate
)
SELECT *
FROM (
   SELECT Milestone
        , MreleaseDate AS DateValue
        , 'Mrelease' AS DateType
   FROM milestonesCTE
   WHERE rn <= 10
   UNION ALL
   SELECT Milestone
        , MprojectDate AS DateValue
        , 'Mproject' AS DateType
   FROM milestonesCTE
   WHERE rn <= 10
) upvt
PIVOT (
   MAX(DateValue)
   FOR Milestone
   IN ([Functional Certification], 
       [QA Certification / UA Complete], 
       [Code Freeze])
) pvt
;

;WITH milestonesCTE(Milestone, MreleaseDate, MprojectDate,rn)
AS
(
SELECT sc.CodeName, rs.EndDate, t1.EndDate
     , ROW_NUMBER() OVER(ORDER BY rs.EndDate) rn
FROM ReleaseSchedule rs
INNER JOIN StatusCode sc
ON rs.MilestoneCID = sc.CID
LEFT OUTER JOIN(
   SELECT pm.MilestoneCID, pm.EndDate
   FROM ProjectMilestone pm
   INNER JOIN StatusCode sc
   ON pm.MilestoneCID = sc.CID
) as t1 ON rs.MilestoneCID = t1.MilestoneCID
WHERE rs.EndDate >= GetDate()
)
SELECT *
FROM (
   SELECT Milestone
        , MreleaseDate AS DateValue
        , 'Mrelease' AS DateType
   FROM milestonesCTE
   WHERE rn <= 7
   UNION ALL
   SELECT Milestone
        , MprojectDate AS DateValue
        , 'Mproject' AS DateType
   FROM milestonesCTE
   WHERE rn <= 7
) upvt
PIVOT (
   MAX(DateValue)
   FOR Milestone
   IN ([Functional Certification], 
       [QA Certification / UA Complete], 
       [Code Freeze])
) pvt
;

Open in new window

0
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 33538607
Thanks, cyberkiwi!
0
Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

 

Author Comment

by:realcoding
ID: 33542830
what if the milestones will be dynamic?
can i have a sub query fill those?
0
 

Author Comment

by:realcoding
ID: 33542839
PIVOT (
   MAX(DateValue)
   FOR Milestone
   IN ([Functional Certification],
       [QA Certification / UA Complete],
       [Code Freeze])
) pvt
;


can these be a sub query?
[Functional Certification],        [QA Certification / UA Complete],        [Code Freeze]
0
 
LVL 60

Accepted Solution

by:
Kevin Cross earned 500 total points
ID: 33544063
As I said earlier, you will need to use dynamic SQL for that.

http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SQL-Server-2005/A_653-Dynamic-Pivot-Procedure-for-SQL-Server.html

The above article explains the technique needed. And provides as the title suggests a ready made procedure that will dynamically pivot the data for you.
0

Featured Post

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

Question has a verified solution.

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

The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

752 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