您的位置:首页 > 数据库 > Oracle

oracle的一些使用技巧1

2017-10-31 18:52 411 查看
1.使用创建临时表
with student as
(select 101 as sid, '张三' as sname, 10 as sage from dual union
select 102 as sid, '李四' as sname, 20 as sage from dual union
select 103 as sid, '王五' as sname, 30 as sage from dual)
select * from student;

图1
2.查询金额所占比例(使用over,round,to_char)with student as
(select 101 as sid, '北京' as city, 10 as money from dual union
select 102 as sid, '上海' as city, 20 as money from dual union
select 103 as sid, '广州' as city, 30 as money from dual)
select sid, city, money,
to_char(round(money/sum(money) over(),2),'fm9999990.00') as moneyRatio from student;



图3
4.现有两张表(图4)


图4with t_class as
(select 1 as cid, '1班' as className from dual union
select 2 as cid, '2班' as className from dual),
t_student as
(select 101 as sid, '张三' as sname, '北京' as scity, 1 as cid from dual union
select 102 as sid, '李四' as sname, '上海' as scity, 1 as cid from dual union
select 103 as sid, '王五' as sname, '广州' as scity, 1 as cid from dual union
select 104 as sid, '赵六' as sname, '深圳' as scity, 2 as cid from dual union
select 105 as sid, '钱七' as sname, '珠海' as scity, 2 as cid from dual union
select 106 as sid, '孙八' as sname, '厦门' as scity, 2 as cid from dual)(1)统计各班级的学生、来自的城市、以及班级人数(使用wm_concat)
查询结果图


图5
select tc.cid, tc.className,
wm_concat(ts.sid) as c_sid,
wm_concat(ts.sname) as c_sname,
wm_concat(ts.scity) as c_scity,
count(sid) as c_count
from t_class tc
left join t_student ts
on tc.cid = ts.cid
group by tc.cid, tc.className;(2)统计各班级的学生人数
查询结果图


图6

方法一:select t2.cid, t1.className, t2.c_count
from t_class t1
left join (select tc.cid, count(sid) as c_count
from t_class tc
left join t_student ts
on tc.cid = ts.cid
group by tc.cid) t2
on t1.cid = t2.cid;方法二(写法更为简单):
select tc.cid, max(className) as className, count(sid) as c_count
from t_class tc
left join t_student ts
on tc.cid = ts.cid
group by tc.cid;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据库 oracle sql