sql server - Pivot Query that Puts the rows into different columns depending on the value of a column -


There are devices that go through different types of inspection by different people. In my table, there is DeviceID, InspectID, Date and PersosnID for these data. Each device can go through many types of inspection and therefore there should be several rows in the table for that device.

DeviceID InspectID Date PersonID 1 10 1/1/2014 100 1 20 2/2/2014 200 2 10 3/3/2014 300 2 30 4/4/2014 400

I am looking for a pivot query that creates a view of the table where per device is only one line and all types of inspection are shown in the column. Suppose I already know that InspectIDs are only 10, 20 and 30.

  DeviceID Date10 PersonID10 Date20 PersonID20 Date30 PersonID30 1 1/1/2014 100 2/2/2014 200 Zero Filters 2 3/3/2014 300 NULL NULL 4/4/2014 400 >  

I think it can be done with a pivot query but I'm new to very pivoting. Any help would be appreciated.

 ; With CTE1 (Selection Tool Id, 'Date' CAST (Inspector (5) in the form of VARCHAR) [DATE], 'Person' + CAST (InspectID AS VARCHAR (5)) PersonId, PersonId Personon YourTableWHERE DeviceID = 1 UNION Select All DeviceID, 'Date' + CAST (InspectID AS VARCHAR (5)) InspectID, [DATE], Observed as 'Person' + CAST (VCSAR (5), PersonTed Personon from YourTable WHERE DeviceID = 2) SELECT DeviceID, MIN (Case when InspectID = 'Date10' THEN [DATE]] END) Date 10, minute (case when person = 'person 10' then person was spent) PersonId10, MIN (in case When InspectID = 'Date20' then [DATE] END) days 20, minute (In case when PersonId = 'Person20' THEN PERSONNO END) PersonId20, MIN (In case when InspectID = 'Date30' then [DATE] END) Date 30, minute (In case when PersonId = 'Person30' THEN PERSONNO END) from PersonId30 by CTE1 Group DeviceID  

What's here? SQLFiddle


Comments