I have this table of prices
type | year | price
===================
A | 2002 | 200
B | 2002 | 120
C | 2002 | 126
B | 1999 | 100
A | 2004 | 202
A | 2005 | 206
I need a SELECT query to produce 2d array of prices of type A and B in every year they appear, having NULL if there is no data for the given type.
year | price A | price B
========================
1999 | NULL | 100
2002 | 200 | 120
2004 | 202 | NULL
2005 | 206 | NULL
This is basically a
PIVOTbut MySQL does not have aPIVOTfunction so you can replicate it using aCASEstatement with an aggregate function. If you have a known number oftypevalues, then you can hard-code the values:See SQL Fiddle with Demo
Result:
If you have an unknown number of
typesthen you can use a prepared statement:See SQL Fiddle with Demo