I have a following table.
/------------------------------------\
| LocID | Year | Birth | Death | Abc |
|------------------------------------|
| 1 | 2011 | 100 | 60 | 10 |
|------------------------------------|
| 1 | 2012 | 98 | 70 | 20 |
|..... |
\------------------------------------/
I need the output to be (Condition LocID = 1)
/---------------------\
| Event | 2011 | 2012 |
|---------------------|
| Birth | 100 | 98 |
|---------------------|
| Death | 60 | 70 |
|---------------------|
| Abc | 10 | 20 |
\---------------------/
The table may contain more fields based on various requirements... Hence the number of Rows will depend upon the number of fields (ignoring LOCID and YEAR). Columns is constant. Only for 2 years (Year will be given For ex 2012 is given, then need to display 2011 and 2012).
Essentially need to make column name as row values and column value as Column heading...
Any help....
In order to get the result that you want, you will need to both unpivot the current data from columns into rows and then pivot the
year
data from rows into columns.MySQL does not have a PIVOT or UNPIVOT function, so you will need to use a
UNION ALL
query to unpivot and an aggregate function with aCASE
expression to pivot.If you have a known number of values, then you can hard-code values similar to this:
See SQL Fiddle with Demo.
But if you are going to have an unknown number of values, then you will need to use a prepared statement to generate dynamic SQL. The code will be similar to the following:
See SQL Fiddle with Demo. The result for both queries is: