1
1
13124291322019-02-22 17:37:46
MySQL
1312429132, 2019-02-22 17:37:46

SQL. How to get row with max value?

1. I get a table like "Department - Total Salary":
select dept_no,sum(salary) as sum from salaries as s join dept_emp as d on s.emp_no = d.emp_no where s.to_date = '9999-01-01' group by d.dept_no
2. Next, you need to display the department with the Maximum Amount. How I solve it:
select y.dept_no, y.sum from (select max(sum) as max from (select dept_no,sum(salary) as sum from salaries as s join dept_emp as d on s.emp_no = d.emp_no where s.to_date = '9999-01-01' group by d.dept_no) as z) as x join (select dept_no,sum(salary) as sum from salaries as s join dept_emp as d on s.emp_no = d.emp_no where s.to_date = '9999-01-01' group by d.dept_no) as y on x.max = y.sum
Question: How is this done correctly? It's too cumbersome.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2019-02-22
@1312429132

SELECT `dept_no`, sum(`salary`) AS `sum`
  FROM `salaries` AS `s`
  JOIN `dept_emp` AS `d`
    ON `s`.`emp_no` = `d`.`emp_no`
  WHERE `s`.`to_date` = '9999-01-01'
  GROUP BY `d`.`dept_no`
  ORDER BY `sum` DESC
  LIMIT 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question