在没有解析功能的情况下转换SQL查询

时间:2019-05-11 10:17:53

标签: sql oracle oracle11g

我必须在不使用任何Oracle SQL分析功能的情况下转换以下SQL查询:

`SELECT
last_name
,first_name
,from_date
,first_salary
,max_salary
FROM( SELECT
e.last_name, 
e.first_name, 
s.from_date,
RANK() OVER(PARTITIONby e.employee_id order BY s.from_date) rn,
s.salary AS first_salary,
MAX(s.salary) OVER (PARTITION BY e.employee_id) AS max_salary
FROM employees e
JOIN salaries s ON e.employee_id=s.employee_id
) t WHERE rn=1;`

下面的转换好吗?

`SELECT e.last_name,
e.first_name,
min_d.FROM_DATE,
min_s.min_salary,
max_s.max_salary    
FROM employees e,     
(SELECT employee_id, MIN(SALARY) as min_salary FROM SALARIES GROUP BY 
employee_id) min_s,
(SELECT employee_id, MAX(SALARY) as max_salary FROM SALARIES GROUP BY 
employee_id) max_s,
(SELECT employee_id, min("FROM_DATE") as FROM_DATE FROM SALARIES GROUP BY 
employee_id) min_d
where e.employee_id=min_s.employee_id and max_s.employee_id=e.employee_id 
AND MIN_D.employee_id=e.employee_id;`

2 个答案:

答案 0 :(得分:0)

这有点棘手,可能是学习如何使用窗口函数的好方法。

以下是一种合理的方法。它假定没有重复记录(您的原始代码不需要)。

select e.last_name, e.first_name,
       s.first_date,
       (select s2.salary
        from salaries s2
        where s2.employee_id = s.employee_id and
              s2.from_date = s.from_date
       ) as first_salary
       s.max_salary    
from employee e join
     (select s.employee_id,
             min(s.from_date) as first_date,
             max(s.salary) as max_salary
      from salaries s
      group by s.employee_id
     ) s
     on e.employee_id = s.employee_id ;

执行此操作的另一种方法仅使用聚合函数,并且可能写为:

select e.last_name, e.first_name,
       s.first_date, s.first_salary, s.max_salary    
from employee e join
     (select s.employee_id,
             min(s.from_date) as first_date,
             min(s.salary) keep (dense_rank first over order by s.from_date) as first_salary,
             max(s.salary) as max_salary
      from salaries s
      group by s.employee_id
     ) s
     on e.employee_id = s.employee_id ;

这使用了keep功能,并且可能比其他两种解决方案中的任何一种都有更好的性能。

答案 1 :(得分:-1)

Select e.last_name
      ,e.first_name
      ,Min(s.FROM_DATE) as min_from_date
      ,Min(s.SALARY) as min_salary
      ,Max(s.SALARY) as max_salary 
From Employees e 
inner join Salaries s on e.employee_id = s.e.employee_id
group by e.last_name,e.first_name