Oracle SQL3-过程思维转换为集合思维

在写SQL文时,用集合思维写出的执行效果比过程思维写出的有时候要高效率一些。下面用一个简单的例子演示一下什么是过程思维和集合思维。

create table MYJOB
(
  EMPID      VARCHAR2(10),
  JOBNM      VARCHAR2(10),
  SRART_DATE DATE,
  END_DATE   DATE
);
commit;
insert into MYJOB (EMPID, JOBNM, SRART_DATE, END_DATE)
values ('001', 'AA', to_date('01-05-2017', 'dd-mm-yyyy'), to_date('01-06-2017', 'dd-mm-yyyy'));
insert into MYJOB (EMPID, JOBNM, SRART_DATE, END_DATE)
values ('001', 'BB', to_date('01-02-2017', 'dd-mm-yyyy'), to_date('01-04-2017', 'dd-mm-yyyy'));
insert into MYJOB (EMPID, JOBNM, SRART_DATE, END_DATE)
values ('001', 'CC', to_date('01-07-2016', 'dd-mm-yyyy'), to_date('01-09-2016', 'dd-mm-yyyy'));
insert into MYJOB (EMPID, JOBNM, SRART_DATE, END_DATE)
values ('002', 'AA', to_date('01-06-2017', 'dd-mm-yyyy'), to_date('01-07-2017', 'dd-mm-yyyy'));
insert into MYJOB (EMPID, JOBNM, SRART_DATE, END_DATE)
values ('002', 'BB', to_date('01-02-2017', 'dd-mm-yyyy'), to_date('01-05-2017', 'dd-mm-yyyy'));
insert into MYJOB (EMPID, JOBNM, SRART_DATE, END_DATE)
values ('001', 'AA', to_date('01-06-2017', 'dd-mm-yyyy'), to_date('01-07-2017', 'dd-mm-yyyy'));
commit;
数据脚本1
/*集合思维*/
select m.empid
  from (select m2.empid,
               m2.jobnm,
               sum(months_between(m2.srart_date, m2.end_date)) as sum_time
          from myjob m2
         group by m2.empid, m2.jobnm) m
 group by m.empid
having min(m.sum_time) = max(m.sum_time);

/*过程思维*/
with tmp_tbl as(
  select m.empid,
         m.jobnm,
         sum(months_between(m.srart_date, m.end_date)) as month_sum
    from myjob m
   group by m.empid, m.jobnm)
  select distinct m.empid
    from tmp_tbl m
   where not exists (select null
            from tmp_tbl m2
           where m.empid = m2.empid
             -- and m.jobnm = m2.jobnm
             and m.month_sum <> m2.month_sum)

 

转载于:https://www.cnblogs.com/aaron-song/p/7239435.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值