1

次のような 'prices_x' という mysql のテーブルがあります。

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

そして、同じ列で異なる値を持つ「prices_y」と呼ばれる他のものがあります。

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

php でレポート ページを作成したいのですが、まずこれでテーブルを変換する必要があります。特定の日付と時刻ですべてのマシンを表示したいだけですが (その方法は知っています)、列を行に変換する方法がわかりません。すべてを試してみましたが、解決策が見つかりません。

ID マシンの価格_x、価格_y
1 hfmachine 90 50
2 hfmachinex 100 40
3 hfmachiney 100 80
4 hfmacinez 98 76
5 hfchinep 78 89

ありがとう。

4

1 に答える 1

3

実装するこのプロセスはunpivotと呼ばれます。残念ながら、MySQL には UNPIVOT 関数はありませんが、UNION ALL クエリを使用して結果を取得できます。

UNION ALL は、複数の列を複数の行に変換します。fechaテーブルごとにこれを実行してから、hora列名でテーブルを結合できます。クエリは次のようになります。

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;

デモを見る

可能であれば、データのクエリを大幅に簡単にするテーブルの正規化を検討することをお勧めします。

于 2013-05-20T18:52:24.713 に答える