1

I have a table in mysql called 'prices_x' that looks like this:

ID Fecha      Hora  hfmachine1 hcmachinex hfmachiney hfmachinez hfmachinep etc...
1  12/01/01/  00:00 90         100        100        98         78         etc...
2  12/01/02/  01:00 90         100        100        98         78         etc...

and i have other called 'prices_y' with the same columns but with diferents values.

ID Fecha      Hora  hfmachine1 hcmachinex hfmachiney hfmachinez hfmachinep etc...
1  12/01/01/  00:00 50         40          80        76         89         etc...
2  12/01/02/  01:00 60         40          90        30         23         etc.

I want to do a report page with php but first i need to convert my table in this. only want to show all machines in a date and time specific (i know how to do that), but i don't know how to convert my columns to rows, i'm try everything and i don't find a solution.

Id Machine   prices_x, prices_y
1 hfmachine  90        50
2 hfmachinex 100       40
3 hfmachiney 100       80
4 hfmacinez  98        76
5 hfchinep   78        89

Thanks.

Nivla
  • 35
  • 6
  • 2
    Show us [what you've tried](http://mattgemmell.com/2008/12/08/what-have-you-tried/). See [about Stack Overflow](http://stackoverflow.com/about). – John Conde May 20 '13 at 12:59

1 Answers1

3

This process that you want to implement is known an unpivot. Unfortunately MySQL does not have any UNPIVOT function but you can use a UNION ALL query to get the result.

The UNION ALL converts the multiple columns into multiple rows. You can do this for each table and then join the tables on the fecha, hora and column name. The query would be similar to the following:

select x.col, 
  x.price_x,
  y.price_y
from
(
  select id, fecha, hora, 'hfmachine1' col, hfmachine1 price_x
  from prices_x
  union all
  select id, fecha, hora, 'hcmachinex' col, hcmachinex price_x
  from prices_x
  union all
  select id, fecha, hora, 'hfmachiney' col, hfmachiney price_x
  from prices_x
  union all
  select id, fecha, hora, 'hfmachinez' col, hfmachinez price_x
  from prices_x
  union all
  select id, fecha, hora, 'hfmachinep' col, hfmachinep price_x
  from prices_x
) x
left join
(
  select id, fecha, hora, 'hfmachine1' col, hfmachine1 price_y
  from prices_y
  union all
  select id, fecha, hora, 'hcmachinex' col, hcmachinex price_y
  from prices_y
  union all
  select id, fecha, hora, 'hfmachiney' col, hfmachiney price_y
  from prices_y
  union all
  select id, fecha, hora, 'hfmachinez' col, hfmachinez price_y
  from prices_y
  union all
  select id, fecha, hora, 'hfmachinep' col, hfmachinep price_y
  from prices_y
) y
  on x.fecha = y.fecha
  and x.hora = y.hora
  and x.col = y.col;

See Demo

If possible my suggestion would be to look at normalizing the tables which would make querying the data significantly easier.

Taryn
  • 242,637
  • 56
  • 362
  • 405