子查询
何时使用子查询
1. 子查询作为数据源
2. 数据加工
需求:根据不同顾客的所有的账户余额划分区间,进行分组
sql语句实现如下:
select 'Small Fry' name , 0 low_limit , 4999.99 high_limitunion allselect 'Average Joes' name ,5000 low_limit, 9999.99 high_limitunion allselect 'High Hitters' name,10000 low_limit,9999999.99 high_limit;
需求:根据顾客,统计每一个分组里的顾客数目,以了解顾客的经济情况,根据不同的顾客提供对应的服务
思路:
一个顾客有多个账户 (account表里)
group by每个顾客,统计每个顾客的总余额 (这里还涉及到账户类型一定要是ACCOUNT类型才是Customer的Accounts,因为还涉及到保险公司的账户类型,以及借贷的账户类型),所以还要跟产品表,产品类型表连接
根据这个总余额 和 上面的余额分组做 内连接,进行范围查询。(范围查询的内连接,把两张表连接起来,形成一个新的临时表)
最后,根据第3步得到的临时表,按分组名进行分组,group by groups.name,然后根据分组统计每个组里的人数。
4.1 cust_rollup 临时表 为 每个customer的总余额
select groups.name,COUNT(*) num_customersfrom (select a.cust_id ,SUM(a.avail_balance) cust_balance from account a inner join product p on a.product_cd = p.product_cd where p.product_type_cd = 'ACCOUNT' group by a.cust_id ) cust_rollup inner join (select 'Small Fry' name , 0 low_limit , 4999.99 high_limit union all select 'Average Joes' name ,5000 low_limit, 9999.99 high_limit union all select 'High Hitters' name,10000 low_limit,9999999.99 high_limit) groups on cust_rollup.cust_balance between groups.low_limit and groups.high_limit group by groups.name;
不进行group by,可以显示每个分组的顾客id
select groups.name,cust_idfrom (select a.cust_id ,SUM(a.avail_balance) cust_balance from account a inner join product p on a.product_cd = p.product_cd where p.product_type_cd = 'ACCOUNT' group by a.cust_id ) cust_rollup inner join (select 'Small Fry' name , 0 low_limit , 4999.99 high_limit union all select 'Average Joes' name ,5000 low_limit, 9999.99 high_limit union all select 'High Hitters' name,10000 low_limit,9999999.99 high_limit) groups on cust_rollup.cust_balance between groups.low_limit and groups.high_limitorder by groups.name,cust_id ASC;
效果: