0

次のmysqlテーブルがあります:

+----+-----+-----+--------+
| id | sid | tid |  val   |
+----+-----+-----+--------+
|  1 |   1 |   1 | square |
|  2 |   1 |   2 | big    |
|  3 |   1 |   3 | red    |
|  4 |   2 |   1 | circle |
|  5 |   2 |   2 | small  |
|  6 |   2 |   3 | yellow |
+----+-----+-----+--------+

そして、次の結果を得るにはクエリが必要です。

+-----+--------+-------+--------+
| sid | figure | size  | colour |
+-----+--------+-------+--------+
|   1 | square | big   | red    |
|   2 | circle | small | yellow |
+-----+--------+-------+--------+

何か案は?

ありがとう。

4

1 に答える 1

2

新しい列名を決定する方法についての詳細は提供しませんでしたが、データに基づいて、tid列の値に基づいていると推測しています。ケース式で集計関数を使用して、結果を取得できます。

select 
  sid,
  max(case when tid = 1 then val end) figure,
  max(case when tid = 2 then val end) size,
  max(case when tid = 3 then val end) color
from yourtable
group by sid;

デモで SQL Fiddle を参照してください

于 2013-09-25T14:33:23.540 に答える