SQL强化(一)保险业务

保险业务 :

表结构 : 

sql语句 :
/*1. 根据投保人电话查询出
投保人 姓名 身份证号 所有保单 编号 险种 缴费类型*/
SELECT
t2.cust_name,
t2.idcard,
t4.pro_id,
t5.pay_type_name,
t6.protype_name
FROM
contact t1, -- 联系表
customer t2, -- 客户表
holder t3, --
product t4,
pay_type t5,
protype t6
WHERE
t1.contact_text = '15987654565'
AND t1.cust_id = t2.cust_id
AND t3.cust_id = t2.cust_id
AND t3.pro_id = t4.pro_id
AND t4.pay_type = t5.pay_type_id
AND t4.pro_type = t6.protype_id

/*
2. 根据保单号 查询 保单号 保单险种
投保人 姓名 身份证号 被保人 姓名身份证号 和受益人的姓名身份证
*/
SELECT
t1.pro_id,
t1.pro_type,
c1.cust_name,
c1.idcard,
c2.cust_name,
c2.idcard,
c3.cust_name,
c3.idcard
FROM
product t1,
holder t2,
insurer t3,
benefit t4,
customer c1,
customer c2,
customer c3
WHERE
t1.pro_id = '1100012313441122'
AND t1.pro_id = t2.pro_id
AND t2.cust_id = c1.cust_id
AND t1.pro_id = t3.pro_id
AND t3.cust_id = c2.cust_id
AND t1.pro_id = t4.pro_id
AND t4.bene_id = c3.cust_id

/*
4. 找到 所有 投保人 被保人 受益人都是同一个人的 保单
*/
select * from product t1 ,holder t2, insurer t3, benefit t4
where t1.pro_id = t2.pro_id
and t1.pro_id = t3.pro_id
and t1.pro_id = t4.pro_id
and t2.cust_id = t3.cust_id
and t3.cust_id = t4.bene_id

/*
6 找到 各险种中 保费最多的 前三张保单 (分组后排序)*/
select * from(
select row_number() over(partition by pro_type order by premium desc) rn ,
product.* from product
) where rn<=3


//============================================

-- 关于时间 的比较
select * from product where pro_start_date < to_date('2017-04-10 23:12:12','yyyy-mm-dd hh24:mi:ss')
/* 关于时间和字符串的转换

mm 月份 注意不是 MM
mi 分钟

hh24 24小时的小时
hh 12小时的小时

字符串 不能超过 格式的长度
*/
视图
一 : 什么是视图 view

视图(view),也称虚表, 数据不占用物理空间。
视图只有逻辑定义。每次使用的时候,只是重新执行SQL。
一个视图 可以插叙多张表 查询的每张表 叫做基表
修改视图的数据 基表的数据也会改变

二 : 试图的作用
1. 简化查询
2. 规避敏感列
3. 简化权限管理 增加安全性

三: 创建视图 用户需要拥有 create view 权限 grant create view to USERNAME;
-- 授权时 必须使用管理员权限

四 语法:
create [ or replace ] [ force ] view [schema.]view_name
[ (column1,column2,...) ]
as
select ...
[ with check option ] [ constraint constraint_name ]
[ with read only ];
tips:
1 or replace: 如果存在同名的视图, 则使用新视图"替代"已有的视图
2 force: "强制"创建视图,不考虑基表是否存在,也不考虑是否具有使用基表的权限
3 column1,column2,...:视图的列名, 列名的个数必须与select查询中列的个数相同;
如果select查询包含函数或表达式, 则必须为其定义列名.此时, 既可以用column1, column2指定列名, 也可以在select查询中指定列名.
4 with check option: 指定对视图执行的dml操作必须满足“视图子查询”的条件即,对通过视图进行的增删改操作进行"检查",
要求增删改操作的数据, 必须是select查询所能查询到的数据,否则不允许操作并返回错误提示. 默认情况下,
在增删改之前"并不会检查"这些行是否能被select查询检索到.
5 with read only:创建的视图只能用于查询数据, 而不能用于更改数据.


五 : 示例 :
create view customer_contact_inner
as
select t1.cust_name custname,
t1.cust_id custid,
t1.idcard idcard,
t1.age age,
t1.sex sex,
t1.brith birth,
t2.contact_type contacttype,
t2.contact_text text
from customer t1, contact t2
where t1.cust_id = t2.cust_id


select * from customer_contact_inner where custname = '张效民'
这样就减少了查询的逻辑语句

原文地址:https://www.cnblogs.com/pengmengnan/p/6727047.html