OK, I have a sales table that looks like this:
Prod_ID | Store_ID | Date_Sold | Num_Sold 105 | 1010 | 2012-09-21 | 50 105 | 1011 | 2012-09-22 | 20 105 | 1012 | 2012-09-22 | 35 ............................................ 109 | 1010 | 2012-09-21 | 25 109 | 1011 | 2012-09-23 | 15 109 | 1012 | 2012-09-23 | 30
I would like to create a new table or view that looks like this:
Store_ID | 105 | ... | 109 1010 | 50 | ... | 25 1011 | 20 | ... | 15 1012 | 35 | ... | 30
I’m not really sure how to accomplish this. I have seen where people hard code this in, but I don’t want to do that as I have more that 50 different Prod_IDs and they are constantly changing. Is there a way to to this dynamically? I am going to be displaying this data on a webpage via PHP so maybe there is an easier way to do it using PHP?? Let me know if this explanation is unclear.
Thanks in advance!!
In MySQL you will need to use a prepared statement to
PIVOTthe data. Since MySQL does not have aPIVOTfunction, then you will need to use an aggregate function along with aCASE:See SQL Fiddle with Demo
If you had a known number of columns, then you would hard-code the values similar to this:
see SQL Fiddle with Demo