我有一个employee
表,上面有名字和薪水。
我要打印这两列,其中只包含2条记录,即我的最高薪水和最低薪水的雇员的名字。
它应该看起来像这样:
Name Salary
------------------
James 800
Samanth 3000
以下代码不是我想要的,我希望在2列中使用两个代表每个值的名称的最小值和最大值
SELECT
name, MIN(salary), MAX(salary)
FROM
employee
答案 0 :(得分:1)
最佳方法取决于数据库,但是以下方法使用标准SQL:
select max(case when seqnum_asc = 1 then salary end) as min_salary,
max(case when seqnum_asc = 1 then name end) as min_salary_name,
max(case when seqnum_desc = 1 then salary end) as max_salary,
max(case when seqnum_desc = 1 then name end) as max_salary_name
from (select e.*,
row_number() over (order by salary asc) as seqnum_asc,
row_number() over (order by salary desc) as seqnum_desc
from employee e
) e;
答案 1 :(得分:0)
您可以通过多种方式执行此操作。这只是其中之一。如果他们的最低/最高薪水相同,它可能会给出多于2条记录
声明@min int,@max int 从YourTable中选择@ min = min(Salary),@ max = max(Salary)
选择名称,从YourTable中获得薪水,其中Salary = @ min或Salary = @ max
答案 2 :(得分:0)
我用这种方式。你可以这样
DECLARE @minsalary varchar(60)
set @minsalary = (select top 1 concat(Name, ' ', salary) from employee where salary= (select min(salary) from employee)
)
DECLARE @maxsalary varchar(60)
set @maxsalary = (select top 1 concat(Name, ' ', salary) from employee where salary= (select max(salary) from employee)
)
select concat(@maxsalary, ' ', @minsalary)
答案 3 :(得分:0)
如果使用的是mysql,则可以执行以下操作
即使超过1人的最高/最低薪水也可以解决此问题
SELECT *
FROM (
SELECT group_concat(NAME) AS names ,
salary ,
'minimum' AS remarks
FROM employee
GROUP BY salary
ORDER BY salary limit 1)tmp
UNION ALL
SELECT *
FROM (
SELECT group_concat(NAME) AS names ,
salary ,
'maximum' AS remarks
FROM employee
GROUP BY salary
ORDER BY salary DESC limit 1
)tmp1
样本输出
names salary remarks
tom,jolly 10 minimum
sally 10001 maximum
答案 4 :(得分:0)
我终于找到了我想要的简单代码。
select emp_name, salary
from employees
where salary = (select max(salary) from employees)
union all
select emp_name, salary
from employees
where salary = (select min(salary) from employees);
我不知道Union。 谢谢大家的贡献
答案 5 :(得分:0)
您可以通过使用子查询来做到这一点:
SELECT first_name, salary FROM employees
WHERE salary IN ((SELECT MAX (salary) FROM employees), (SELECT MIN (salary) FROM employees))
答案 6 :(得分:-1)
您可以尝试一下。示例输出。
name MAX(salary) MIN(salary)
George 9200 9200
James 5000 100
Kanye 3200 3200
Nicole 4500 4500
Samanth 3000 2300
Umut 1500 250
Vladimir 2300 330
示例表格值
id name salary
1 James 800
2 Samanth 3000
3 Umut 1500
4 Umut 250
5 Nicole 4500
6 George 9200
7 Kanye 3200
8 Vladimir 2300
9 Vladimir 1000
10 Vladimir 330
11 James 5000
12 James 100
13 Samanth 2300
SELECT name, MAX(salary), MIN(salary) FROM employee GROUP BY name;