如何找到旅行次数最多的员工?

时间:2019-01-03 12:22:07

标签: sql oracle

我需要将从今年开始到今天旅行次数最多的员工的薪水提高5%。有两种类型的员工:司机和女主人。这是我的桌子:

CREATE TABLE Employe(  
  nb_emp VARCHAR2(5),  
  salary NUMBER
);

nb_emp是主键。

CREATE TABLE Trip(  
  id_trip NUMBER,  
  driver VARCHAR2(5),  
  hostess VARCHAR(5),  
  date_trip DATE
);

id_trip是主键,驱动程序,并且hostess来自表nb_emp的引用Employee

这是我对驱动程序的查询:

update employe
set salary = salary*0.05 + salary
where nb_emp in (
    select driver 
    from trip t
    where 
        nb_emp = t.driver
        and t.date_trip >= TRUNC(SYSDATE,'YEAR')
        AND t.date_trip < SYSDATE
        and t.id_trip in (
            Select count(tt.id_trip) from trip tt having count(tt.id_trip) = (
                Select Max(s) FROM (select count(ttt.id_trip) as s FROM trip ttt
            )
        )
    )
);

1 个答案:

答案 0 :(得分:0)

寻找出差最多的工人的方法之一:

select emp 
  from (
    select emp, count(1) cnt, max(count(1)) over () mcnt
      from (
        select driver as emp from trip where date_trip between trunc(sysdate, 'year') and sysdate
        union all
        select hostess from trip where date_trip between trunc(sysdate, 'year') and sysdate)
      group by (emp))
  where cnt = mcnt;

update语句中使用此查询,如下所示:

update employe set salary = salary * 1.05 
  where nb_emp in (
    select emp 
      from (
        select emp, count(1) cnt, max(count(1)) over () mcnt
          from (
            select driver as emp from trip where date_trip between trunc(sysdate, 'year') and sysdate
            union all
            select hostess from trip where date_trip between trunc(sysdate, 'year') and sysdate)
          group by (emp))
      where cnt = mcnt);

我的测试数据:

create table employe(nb_emp, salary) as (
    select 'D1', 1000 from dual union all
    select 'D2', 1000 from dual union all
    select 'H1', 1000 from dual union all
    select 'H2', 1000 from dual union all
    select 'H3', 1000 from dual );

create table trip (id_trip, driver, hostess, date_trip) as (
    select 1, 'D1', 'H1', date '2019-01-01' from dual union all
    select 2, 'D1', 'H2', date '2019-01-01' from dual union all
    select 3, 'D1', 'H2', date '2019-01-02' from dual union all
    select 4, 'D2', 'H1', date '2019-01-02' from dual union all
    select 5, 'D2', 'H2', date '2019-01-03' from dual );

驾驶员D1和女主人H2出行最多(3),他们的薪水提高到1050