Pivoting a Query

I have a query with the follow results

Date TotalUnitsAvail RentedDuringMonth VacatedDuringMonth NetRentals
Jan-13 260 17 11 6
Feb-13 260 11 6 5
Mar-13 260 19 14 5
Apr-13 259 14 13 1
May-13 260 11 16 -5
Jun-13 260 16 17 -1
Jul-13 260 14 14 0

and I need to pivot the data to get

Date Jan-13 Feb-13 Mar-13 Apr-13 May-13 Jun-13 Jul-13
TotalUnitsAvail 260 260 260 259 260 260 260
RentedDuringMonth 17 11 19 14 11 16 14
VacatedDuringMonth 11 6 14 13 16 17 14
NetRentals 6 5 5 1 -5 -1 0

How do I go about getting this done?

September 14th, 2015 5:04pm

Give this a shot:

DECLARE @table TABLE (Date VARCHAR(6), TotalUnitsAvail INT, RentedDuringMonth INT, VacatedDuringMonth INT, NetRentals INT)
INSERT INTO @table (Date, TotalUnitsAvail, RentedDuringMonth, VacatedDuringMonth, NetRentals) VALUES
('Jan-13', 60, 17, 11, 6 ),
('Feb-13', 60, 11, 6, 5 ),
('Mar-13', 60, 19, 14, 5 ),
('Apr-13', 59, 14, 13, 1 ),
('May-13', 60, 11, 16, -5),
('Jun-13', 60, 16, 17, -1),
('Jul-13', 60, 14, 14, 0 )



;WITH tua AS (
SELECT tuay, 
MAX([Jan-13]) AS [Jan-13],MAX([Feb-13]) AS [Feb-13],MAX([Mar-13]) AS [Mar-13],MAX([Apr-13]) AS [Apr-13],MAX([May-13]) AS [May-13],MAX([Jun-13]) AS [Jun-13],MAX([Jul-13]) AS [Jul-13]
 FROM @table
   UNPIVOT (
            tuax FOR tuay IN (totalUnitsAvail)
           ) tua
   PIVOT (
          MAX(tuax) FOR date IN ([Jan-13], [Feb-13], [Mar-13], [Apr-13], [May-13], [Jun-13], [Jul-13]) 
         ) p
 GROUP BY tuay
), rdm AS (
SELECT rdmy, 
MAX([Jan-13]) AS [Jan-13],MAX([Feb-13]) AS [Feb-13],MAX([Mar-13]) AS [Mar-13],MAX([Apr-13]) AS [Apr-13],MAX([May-13]) AS [May-13],MAX([Jun-13]) AS [Jun-13],MAX([Jul-13]) AS [Jul-13]
 FROM @table
   UNPIVOT (
            rdmx FOR rdmy IN (rentedDuringMonth)
           ) rdm
   PIVOT (
          MAX(rdmx) FOR date IN ([Jan-13], [Feb-13], [Mar-13], [Apr-13], [May-13], [Jun-13], [Jul-13]) 
         ) p
 GROUP BY rdmy
)

SELECT *
  FROM tua 
UNION ALL
SELECT *
  FROM rdm

Free Windows Admin Tool Kit Click here and download it now
September 14th, 2015 5:33pm