user1504583
user1504583

Reputation: 235

MySQL or PHP Turning rows into columns dynamically

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!!

Upvotes: 1

Views: 1676

Answers (2)

sfell77
sfell77

Reputation: 986

So the view above is the output in MySQL. PHP allows you to lay out the data however you want and will resolve your issue. You would make a repeating row in a table (html for layout, php for repeating) and inside that table put the output of your MySQL statement called through PHP.

There's a good amount of code that goes into this both for setting up the MySQL connection (PHP) and of course laying out your table (HTML).

Upvotes: 1

Taryn
Taryn

Reputation: 247700

In MySQL you will need to use a prepared statement to PIVOT the data. Since MySQL does not have a PIVOT function, then you will need to use an aggregate function along with a CASE:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'sum(case when Prod_ID = ''',
      Prod_ID,
      ''' then Num_Sold end) AS ''',
      Prod_ID, ''''
    )
  ) INTO @sql
FROM  yourtable;

SET @sql = CONCAT('SELECT store_id, ', @sql, ' 
                  FROM yourtable 
                   GROUP BY store_id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

See SQL Fiddle with Demo

If you had a known number of columns, then you would hard-code the values similar to this:

select store_id,
  sum(case when prod_id = 105 then Num_Sold end) as '105',
  sum(case when prod_id = 109 then Num_Sold end) as '109'
from yourtable
group by store_id

see SQL Fiddle with Demo

Upvotes: 2

Related Questions