需要关于select查询的建议,多行应该变成列

ui7jx7zq  于 2021-06-16  发布在  Mysql
关注(0)|答案(1)|浏览(259)

这个问题在这里已经有答案了

如何在mysql中返回pivot表输出(9个答案)
去年关门了。
我有一张table:

id     data-type       data-answer
-----------------------------------
1      car             honda
1      color           yellow
1      engine          gasoline
2      car             bmw
2      color           black
3      engine          diesel

需要建议,如何编写select以使其在输出中:

id       car        color        engine
-----------------------------------------
1        honda      yellow       gasoline
2        bmw        black        diesel

表格中的数据是为了简化这个例子。已经在网上搜索了两天了。找不到解决方案。需要指导搜索什么。

1aaf6o9v

1aaf6o9v1#

你需要条件聚合 PIVOT :

select id, 
       max(case when data-type = 'car' then data_answer end) as car,
       max(case when data-type = 'color' then data_answer end) as color,
       max(case when data-type = 'engine' then data_answer end) as engine
from table t
group by id;

相关问题