Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

How to dynamically pivot on value?

$
0
0

Hi All,

I have a table of data that looks like this:

However, I needed to pivot on the Inspector Column to look like this:

My problem is that these values for the Inspector field are dynamic (they can change over time). So, while my SQL pivots correctly, as you can see, I had to hard code the values for [bradd],[CoryJ],[jeremiahb],[kenth]. I don't want to do that. I guess I want to use some kind of array or something?? But I have no idea how to do that within the context of this pivoting.

SELECT 
Ops_Group,
Insp_Cycle,
MyYear,
MyMonth,
CASE MyMonth
  WHEN 'January' THEN 1
  WHEN 'February' THEN 2
  WHEN 'March' THEN 3
  WHEN 'April' THEN 4
  WHEN 'May' THEN 5
  WHEN 'June' THEN 6
  WHEN 'July' THEN 7
  WHEN 'August' THEN 8
  WHEN 'September' THEN 9
  WHEN 'October' THEN 10
  WHEN 'November' THEN 11
  WHEN 'December' THEN 12
END as MonthOrder,

[bradd],[CoryJ],[jeremiahb],[kenth]

FROM


(        
SELECT
  Ops_Group,
  Insp_Cycle,
  Inspector,
  DateName( month , DateAdd( month , MONTH(GPS_Date) , -1 ) )  AS MyMonth,
  YEAR(GPS_Date)  AS MyYear,
  COUNT(Inspector) AS CountOfInspector
FROM
  dbo.Detailed_OH_Dist
LEFT JOIN
  dbo.Employee_Group
ON
  dbo.Detailed_OH_Dist.Inspector = dbo.Employee_Group.username
WHERE
  GPS_Date >='2014-01-01 00:00:01'
GROUP BY
  Ops_Group,
  Insp_Cycle,
  Inspector,
  MONTH(GPS_Date),
  YEAR(GPS_Date)
HAVING
  (dbo.Employee_Group.Ops_Group='Meters') AND (dbo.Detailed_OH_Dist.Insp_Cycle='Off-Cycle')

--ORDER BY
--  MONTH(GPS_Date)
) AS SourceTable

-- ================= End Source

-- ================= Begin Pivot

PIVOT
(
Sum(CountOfInspector)
FOR Inspector IN ([bradd],[CoryJ],[jeremiahb],[kenth])
) AS PivotTable

ORDER BY
MonthOrder

Thanks for your assistance,

:) John


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>