Mysql行到列

时间:2013-09-25 14:28:14

标签: mysql rows

我有以下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 |
+-----+--------+-------+--------+

有什么想法吗?

感谢。

1 个答案:

答案 0 :(得分:2)

您没有提供有关如何确定新列名称的任何详细信息,但根据您的数据,我猜测它基于tid列中的值。您可以使用带有case表达式的聚合函数来获取结果:

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 with Demo