SQL分組最大值

2021-10-08 03:37:56 字數 1833 閱讀 9691

employee表包含所有員工資訊,每個員工有其對應的 id, salary 和 department id。

+----+-------+--------+--------------+

| id | name | salary | departmentid |

+----+-------+--------+--------------+

| 1 | joe | 70000 | 1 |

| 2 | henry | 80000 | 2 |

| 3 | sam | 60000 | 2 |

| 4 | max | 90000 | 1 |

+----+-------+--------+--------------+

department表包含公司所有部門的資訊。

+----+----------+

| id | name |

+----+----------+

| 1 | it |

| 2 | sales |

+----+----------+

編寫乙個 sql 查詢,找出每個部門工資最高的員工。例如,根據上述給定的**,max 在 it 部門有最高工資,henry 在 sales 部門有最高工資。

+------------+----------+--------+

| department | employee | salary |

+------------+----------+--------+

| it | max | 90000 |

| sales | henry | 80000 |

+------------+----------+--------+

select a.name as department, b.name as employee, b.salary 

from department a join

(select a.name, a.salary, a.departmentid

from employee a

where

(select

count(*

)from employee b

where a.departmentid = b.departmentid

and a.salary < b.salary

)<

1) b

on a.id = b.departmentid

select a.name as department, b.name as employee, b.salary 

from department a join

(select c.name, c.salary, c.departmentid

from employee c,

(select departmentid,

max(salary)

as salary

from employee

group

by departmentid

) dwhere c.departmentid = d.departmentid

and c.salary = d.salary

) bon a.id = b.departmentid;

SQL分組求最大值

訂單操作記錄表,需要獲取每個訂單最新的操作更新時間,以及操作id。使用 over 以及 row number 來實現 select from select operationid,orderno,updatetime,row number over partition by orderno orde...

sql多表查詢分組最大值

問題描述 有三張表 學生表student id,name id為主鍵 課程表subject id,name id為主鍵 分數表score studentid,subjectid,score 其中studentid與subjectid為聯合主鍵,一句sql語句查詢出 學號,姓名,課程名,課程最高分.模...

sql 分組後的最大值

friday february 10,2006 03 29pm cst select customerid,max balance from temptable1 group by customerid 就可以達到目的了,我竟然半天不知道怎麼下手。看來是被上次max a,b 問題嚇怕了。msn 的這...