Question

I've been looking for how to do this and I haven't been able to find an example

I have data that looks like this:

batchid       wigitid
-------       -------
538217        MT8
538217        MT6
538217        M89A
538218        MT8
538218        M89D
538218        M90

I want to flip the data so it looks like this:

BatchId  MT8 MT6 M89A M89D  M90
-------  --- --- ---  ----  ---
538217    *   *   *
538218    *            *     *

I can loop through the records via a cursor, however I believe that there might be a better way.

Was it helpful?

Solution

how about this.

Select *
From (
    Select batchid, wigitid, '*' wigitname
    From BATCHMAST
) As BMast
Pivot (MAX(wigitname) For WigitId In ([MT8],[MT6],[M89A],[M89D],[M90])) As Pvt

OR try below also if you dont' want null in result

Select batchid, 
    ISNULL([MT8],'') [MT8],
    ISNULL([MT6],'')[MT6],
    ISNULL([M89A],'')[M89A],
    ISNULL([M89D],'')[M89D],
    ISNULL([M90],'')[M90]
From (
Select batchid, wigitid, '*' wigitname
From BATCHMAST
) As BMast
Pivot (MAX(wigitname) For WigitId In ([MT8],[MT6],[M89A],[M89D],[M90])) As Pvt

OTHER TIPS

Try the following code SQL Fiddle

SELECT 
  BatchID, 
  REPLACE(NULLIF(MT6,0), 1, '*') AS MT6,
  REPLACE(NULLIF(MT8,0), 1, '*') AS MT8,
  REPLACE(NULLIF(M89A,0), 1, '*') AS M89A,
  REPLACE(NULLIF(M89D,0), 1, '*') AS M89D,
  REPLACE(NULLIF(M90,0), 1, '*') AS M90
FROM 
      (
   SELECT BatchID, WigitID FROM Information
  ) a

PIVOT

  (
    COUNT(WigitID) FOR WigitID IN (MT6, MT8, M89A, M89D, M90)
  ) b
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top