SQL把同一个人的不同字段在同一行显示出来

问题遇到的现象和发生背景

pid去查学生表,cid查项目表,把同一个cid的不同费用显示在同一行。group by id 不管事呢

我想要达到的结果

img

说下数据库类型,不同的数据库有不同的行列转换方式


题主说是mysql 5.7,那就用下面这个方式吧

select id,
sum(case when cid=5 then amount else 0 and) cid5,
sum(case when cid=1 then amount else 0 and) cid1,
sum(case when cid=3 then amount else 0 and) cid3,
sum(case when cid=21 then amount else 0 and) cid21
 fromgroup by id;

关键你这个amount的个数不是固定的,要转列的话不好做,如果只是要显示在同一行,你可以使用GROUP_CONCAT 函数,这样
select 字段,GROUP_CONCAT(你想在同一行显示的字段)
from 表
group by 字段