tags:

views:

68

answers:

1

I have a table that stores records like this:

name     | stat  | value
--------------------------
object1  | stat1 | val1
object1  | stat2 | val2
object1  | stat3 | val3
object1  | stat4 | val4

But I would like to query the data so it returns rows like this

name    | stat1| stat2| stat3| stat4
-------------------------------------
object1 | val1 | val2 | val3 | val4

Would I use case statements, or how would accomplish something like this? My example shows only 4 possible stats, but hopefully I can create something dynamic enough where if I add new stats in the future, the query won't have to be rewritten. If that is not possible, what are my options?

+3  A: 

Typical pivot query:

  SELECT t.name,
         MAX(CASE WHEN t.stat = 'stat1' THEN t.value ELSE NULL END) AS stat1,
         MAX(CASE WHEN t.stat = 'stat2' THEN t.value ELSE NULL END) AS stat2,
         MAX(CASE WHEN t.stat = 'stat3' THEN t.value ELSE NULL END) AS stat3,
         MAX(CASE WHEN t.stat = 'stat4' THEN t.value ELSE NULL END) AS stat4
    FROM TABLE t
GROUP BY t.name

Being that values need to be statically assigned, this query needs to be converted to dynamic SQL if you want it to handle a dynamic situation - use MySQL's Prepared Statement syntax for dynamic SQL...

OMG Ponies
Thanks. This works beautifully.
Hallik