今天一朋友去面试,面试官出了一个数据库查询问题,挺难做的。呵呵 ,贴出来跟大家分享下:
pid pnum sid
1 10 1
1 12 2
2 8 3
3 11 1
3 10 3
写一个查询语句使其表现为:
pid s1id s2id s3id
1 10 12 0
2 0 0 8
3 11 0 10
解决办法:
select pid,
sum(case when sid =1 then pnum else 0 end) as 's1id',
sum(case when sid =2 then pnum else 0 end) as 's2id',
sum(case when sid =3 then pnum else 0 end) as 's3id'
from xyz(表名)
group by pid
order by pid
SQL经典查询
最新推荐文章于 2024-11-03 11:50:36 发布