Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2012 Pivot Table

I need to create a query that shows the results in a pivot table.

I have a table that is updated regularly with clients Build Status Changes

WE have 8 stages to a build

  • 115 Land Purchased
  • 116 Foundations
  • 117 Timber Kit Erected / Wall Plate Level
  • 118 Wind & Water Tight
  • 119 1st Fix & Plastering
  • 120 Final Fit Out
  • 121 Completed
  • 122 Redeemed

Here is my query

SELECT 
    s.ProjectStage, su.DateStageChanged, p.FK_ID As ID,
    s.LongDesc AS BuildType, su.FK_StageID  
FROM 
    [dbo].[tbl_StageUpdates] AS su
LEFT JOIN
    [dbo].[tbl_Stage] AS s ON su.FK_StageID = s.id
LEFT JOIN 
    tbl_Projects AS p ON su.FK_ProjectID = p.PK_ProjectID
WHERE 
    s.LongDesc = 'New Build'
GROUP BY 
    p.FK_ID, s.ProjectStage, su.DateStageChanged, s.LongDesc, su.FK_StageID
ORDER BY 
    su.FK_StageID ASC

ID is the clients ID what i would like is have the query display the information like this:

enter image description here

Is it possible to do?

Any help on this would be greatly appreciated

Cheers

like image 487
RustyHamster Avatar asked May 31 '26 07:05

RustyHamster


1 Answers

If you've only 8 stages, you could use CASE...WHEN and GROUP BY to archive your expected output. I think it's more readable than using PIVOT function. Furthermore, it's T-SQL and be easier to migrate to other DBMS.

SELECT 
   ID, 
   BuildType,
   MAX(CASE FK_StageID WHEN 115 THEN DateStageChanged ELSE NULL END) AS [Land Purchased],
   MAX(CASE FK_StageID WHEN 116 THEN DateStageChanged ELSE NULL END) AS [Foundations],
   MAX(CASE FK_StageID WHEN 117 THEN DateStageChanged ELSE NULL END) AS [Timber Kit Erected / Wall Plate Level],
   MAX(CASE FK_StageID WHEN 118 THEN DateStageChanged ELSE NULL END) AS [Wind & Water Tight],
   MAX(CASE FK_StageID WHEN 119 THEN DateStageChanged ELSE NULL END) AS [1st Fix & Plastering],
   MAX(CASE FK_StageID WHEN 120 THEN DateStageChanged ELSE NULL END) AS [Final Fit Out],
   MAX(CASE FK_StageID WHEN 121 THEN DateStageChanged ELSE NULL END) AS [Completed],
   MAX(CASE FK_StageID WHEN 122 THEN DateStageChanged ELSE NULL END) AS [Redeemed]
FROM
   (
    -- original query  
        SELECT 
            s.ProjectStage, su.DateStageChanged, p.FK_ID As ID,
            s.LongDesc AS BuildType, su.FK_StageID  
        FROM 
            [dbo].[tbl_StageUpdates] AS su
        LEFT JOIN
            [dbo].[tbl_Stage] AS s ON su.FK_StageID = s.id
        LEFT JOIN 
            tbl_Projects AS p ON su.FK_ProjectID = p.PK_ProjectID
        WHERE 
            s.LongDesc = 'New Build'
        GROUP BY 
            p.FK_ID, s.ProjectStage, su.DateStageChanged, s.LongDesc, su.FK_StageID
    -- original query           
   )  Data 
GROUP BY 
   ID, BuildType
like image 162
Trung Duong Avatar answered Jun 02 '26 23:06

Trung Duong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!