AspDotNet

The leaves of the tree are so exuberant ,because the root of the tree is so deep.
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

SQL灵活使用:分组查询各组的详细记录

Posted on 2008-11-27 22:04  Apple Yang  阅读(755)  评论(0)    收藏  举报

QQ群中遇到一位网友,提到这么一个问题:如何将下述记录集

姓名   科目  分数
张三   语文  30
张三   数学  50
张三   英语  70
李四   语文  50
李四   数学  80
李四   英语  90

通过SQL查询转变成

姓名  语文  数学 英语
张三  30    50   70
李四  50    80   90 

他人(三叶虫)提供的一个解决方案值得借鉴:

select 姓名 as 姓名 ,
max(case 科目 when '语文' then 分数 else 0 end) 语文,
max(case 科目 when '数学' then 分数 else 0 end) 数学,
max(case 科目 when '英语' then 分数 else 0 end) 英语
from tb
group by 姓名

很好使,再次谢谢那位网友!