在多行应成为列的SELECT查询上需要建议

时间:2019-01-04 15:23:05

标签: mysql sql

我有一张桌子:

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

表中的数据是为了简化示例。 尝试在互联网上搜索2天。找不到解决方案。需要指导搜索内容。

1 个答案:

答案 0 :(得分:1)

您需要条件聚合,您可以执行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;