在多个表中选择最高值

时间:2014-08-05 08:59:58

标签: sql

我有以下表格

Table Name : tHREmployee

EmployeID#      Employee    DepartmentID    DesignationID     DOB           BasicPay
101             Ajith       101             102              10/Feb/1982    10000
102             Aarathy     NULL            101              15/Mar/1981    15000
103             Aruna       102             NULL             20/Sep/1980    5000
104             Ambily      101             NULL             20/Sep/1980    5000
105             Anjaly      NULL            101              20/Sep/1980    10000
106             Babitha     103             NULL             20/Sep/1981    20000 



Table Name : tHRDepartment
DepartmentID#   Code    Department
101             500     Production
102             501     HR
103             502     Finance
105             503     Marketing


Table Name : tHRDesignation

DesignationID#  Designation

101             Executive
102             Manager

如何为sql中每个部门的基本工资最高的员工显示员工详细信息(员工,部门,指定,basicPay)?

2 个答案:

答案 0 :(得分:0)

在Oracle中,这应该可以帮助您

WITH CTE AS 
(
  SELECT DepartmentID    , MAX(BasicPay) MAXPAY FROM tHREmployee 
  GROUP BY DepartmentID    
)
SELECT E.EmployeID EMPid, E.Employee  EMP_NAME , DPT.Department DPT_NAME, 
DSG.Designation DSG_NAME, BASICPAY

FROM CTE, tHREmployee E,tHRDepartment DPT, Designation DSG
WHERE 
E.BASICPAY = MAXPAY 
AND E.DepartmentID  = CTE.DepartmentID    
AND E.DepartmentID  = DPT.DepartmentID    
AND E.DesignationID = DSG.DesignationID         

在其他数据库中,类似的内容可以帮助您:

SELECT E.EmployeID EMPid, E.Employee  EMP_NAME , DPT.Department DPT_NAME, 
DSG.Designation DSG_NAME, BASICPAY
FROM tHREmployee E,tHRDepartment DPT, Designation DSG
WHERE 
E.DepartmentID  = CTE.DepartmentID    
AND E.DepartmentID  = DPT.DepartmentID    
AND E.DesignationID = DSG.DesignationID   
AND E.BASICPAY IN 
( SELECT MAX(EE.BASICPAY) FROM tHREmployee EE GROUP BY DPT.DepartmentID   )

答案 1 :(得分:0)

选择A.Employee,B.Department,c.Designation,a.BAsicPay from Employee A内部联接部门B,A.Department = B.DepartmentID左边连接指定C on A.designationID = C.DesignationID内部联接(选择DepartmentID,max(BasicPay)作为来自EmployID组的BasicPay by DepartmentID)为s2 在s2.DepartmentID = A.DepartmentID和A.BAsicPay = s2.BasicPAy