2017-04-11 69 views
-2

我必須找到 部門的最低工資高於部門的平均工資。超過分區最低的大於平均分

+1

低薪怎麼能高於同一部門的平均薪水? – Teja

+1

表格架構?樣本數據?預期結果?或者我們應該拿起水晶球? :-) –

+0

請參閱[How to ask](http://stackoverflow.com/help/how-to-ask)和[Minimal,Complete,and Verifiable example](http://stackoverflow.com/help/mcve ) – bc004346

回答

1

由於您沒有提供表格模式,我假設一個關係emp(empid,deptid,salary)。然後你就可以找到每個部門的工資分鐘這是比平均工資在這個部門更大:

select emp.deptid, min(emp.salary) 
from ( 
    select deptid, avg(salary) avg_sal 
    from emp group by deptid) 
x join emp on x.deptid = emp.deptid 
where emp.salary >= x.avg_sal 
group by emp.deptid 

如果你也想獲得員工 - 你不要在你的問題需要 - 那麼你就可以請使用row_number()

; with cte as (
    select rn = row_number() over (partition by emp.deptid order by emp.salary asc), emp.* 
    from 
    (
     select deptid, avg(salary) avg_sal 
     from emp 
     group by deptid 
    ) x join emp on x.deptid = emp.deptid 
    where emp.salary >= x.avg_sal 
) 
select x.empid, x.deptid, x.salary 
from cte 
where rn = 1