1.预期结果(以图书借阅为例)
查询计算机类图书的总价格和总册数
2. 代码
select
case when bno is not null then bno else'合计'end bno,
case when bno is not null then bname else null end bname,
sum(bprice)as bprice,sum(bcount)as Bcount ,
sum(Bprice*Bcount)as '总价格'
from(select bno ,bname, bprice,Bcount,Bprice*Bcount as '总价格'
from book where Bkind='计算机')as a
group by bno,bname with rollup
having bno is null or bname is not null
3.解释
select bno ,bname, bprice,Bcount,Bprice*Bcount as '总价格'
from book where Bkind='计算机'
这一段为基础数据,查询为除合计外的结果。
第一个case函数意为bno不为空时显示为合计。
group by bno,bname with rollup
这里为结果加bno和bname的合计
最后having过滤去掉多余的合计结果
4.总览
5.union方法
这里就不多解释了