数据库行列转换
实现只显示为某值的字段,可以通过行列转换实现。
以下是以sql server为例来说明:
select b.stu_name,
max(case a.subject when '语文' then a.grade else '' end) as 语文,
max(case a.subject when '数学' then a.grade else '' end) as 数学,
max(case a.subject when '英语' then a.grade else '' end) as 英语
from stu_grade a,stu_master b
where a.stu_no=b.stu_no
group by b.stu_name
数据库为oralce的话执行
select b.stu_name,
max(case a.subject when '语文' then to_char(a.grade) else '' end) as 语文,
max(case a.subject when '数学' then to_char(a.grade) else '' end) as 数学,
max(case a.subject when '英语' then to_char(a.grade) else '' end) as 英语
from stu_grade a,stu_master b
where a.stu_no=b.stu_no
group by b.stu_name
⑵ 写sql,怎么将查询结果的行列转换呀
有意思的问题 给出一个参考的URL: 假设你表是这样的结构部件 入库日期 入库数量 A 1/1 10 A 1/1 5 A 1/2 10 B 1/5 10 其实就是两种方法,假设你的数据库是11以前的,只能先定义好查哪天到哪天 然后那么 selct 部件, sum( decode(入库日期=1号,入库数量,0), sum( decode(入库日期=2号,入库数量,0), 以此类推 from 入库表 group BY 部件(原理上就是将不是这天的变成0,再合计)要是Oracle数据库是11的话,就简单了,直接pivot搞定 pivot语法就不说了,网上一堆一堆的 ~