我正在处理一个SQL查询。
表名:employees
。
我希望在SQL中使用其员工姓名获取MAX
和MIN
sal。
我知道如何处理MAX
或MIN
。但是我们怎样才能在一个查询中做到这一点?
我需要一个单行输出,如下所示:
e1.name AS MaxName, MAX(e1.sal) AS MaxSalary, e2.name AS MinName, MIN(e2.sal) AS MinSalary
答案 0 :(得分:1)
两种方式:
使用 Analytic 功能:
SQL> WITH DATA AS
2 ( SELECT MIN(sal) min_sal, MAX(sal) max_sal FROM emp
3 )
4 SELECT
5 (SELECT e.ename FROM DATA t, emp e WHERE e.sal = t.min_sal AND ROWNUM =1
6 ) min_name,
7 (SELECT t.min_sal FROM DATA t, emp e WHERE e.sal = t.min_sal AND ROWNUM =1
8 ) min_sal,
9 (SELECT e.ename FROM DATA t, emp e WHERE e.sal = t.max_sal AND ROWNUM =1
10 ) max_name,
11 (SELECT t.max_sal FROM DATA t, emp e WHERE e.sal = t.max_sal AND ROWNUM =1
12 ) max_sal
13 FROM dual;
MIN_NAME MIN_SAL MAX_NAME MAX_SAL
---------- ---------- ---------- ----------
SMITH 800 KING 5000
使用内嵌视图:
[view2 buttonClickCheck:cell];
答案 1 :(得分:1)
在单个选择中:
SELECT MIN( salary ) AS MinSalary,
MIN( name ) KEEP ( DENSE_RANK FIRST ORDER BY salary ASC ) AS MinName,
MAX( Salary ) AS MaxSalary,
MAX( name ) KEEP ( DENSE_RANK LAST ORDER BY salary ASC ) AS MaxName
FROM Employees;
答案 2 :(得分:0)
以下解决方案适用于MySQL,这是您在发布问题时最初使用的标记之一。
您可以对自己执行CROSS JOIN
employees
表,以查找最大名称/工资,并查询最小名称/工资。
SELECT e1.name AS MaxName, MAX(e1.sal) AS MaxSalary,
e2.name AS MinName, MIN(e2.sal) AS MinSalary
FROM employees e1 CROSS JOIN employees e2
点击下面的链接查看正在运行的演示。我实际上包括名称/工资对,但如果你不想要它们,你可以删除它们。
答案 3 :(得分:0)
尝试类似:
select max(sal), min(sal), employee_id
from employees
group by employee_id;
之后,您可以加入它以获取名称。也许你也可以按姓名和身份分组。
答案 4 :(得分:0)
假设您使用的是Oracle,请尝试此操作。首先,我们按升序和降序获取rownumber,然后进行交叉连接。
with employee(id,name,sal) as
(select 1,'a',1000 from dual union all
select 3,'c',1500 from dual union all
select 2,'b',2000 from dual) --temp table to recreate the scenario
, enew as(
select e.*,row_number() over (order by sal) as salasc,row_number() over (order by sal desc) as saldesc from employee e
) --temp table to find the rownumber in ascending and descending order
--original query
select * from (select id as minsalid,name as minsalempname,sal as minsal from enew
where salasc=1)
cross join
(select id as maxsalemp,name as maxsalempname,sal as maxsal from enew
where saldesc=1)