我可以将group_by分成列

时间:2017-12-05 22:02:25

标签: mysql group-by pivot-table

+---------+-------+----------+
| number  | type  |   price  |
+---------+-------+----------+
|    1    |   A   |   7.00   | 
|    1    |   B   |   3.00   | 
|    2    |   A   |   1.00   | 
|    2    |   B   |   2.00   | 
|    3    |   A   |   6.00   | 
|    3    |   B   |   9.00   |
+---------+-------+----------+

如果我有一个类似上面的示例表的表。是否可以运行一个查询,该查询将导致像mysql中的以下示例一样的表?

+---------+---------+----------+
| number  |    A    |     B    |
+---------+---------+----------+
|    1    |   7.00  |   3.00   | 
|    2    |   1.00  |   2.00   | 
|    3    |   6.00  |   9.00   | 
+---------+---------+----------+

1 个答案:

答案 0 :(得分:2)

select number,
       min(case when `type` = 'A' then price end) as A,
       min(case when `type` = 'B' then price end) as B
from your_table
group by number