2016-04-16 71 views
2

我有兩個表一個表有DEPTID,EMPID,工資和其他具有表EMPID,名顯示,大於DEPTID平均工資明智

Table1 
+--------+-------+--------+ 
| deptid | empid | salary | 
+--------+-------+--------+ 
| coe |  1 | 19000 | 
| coe |  2 | 13000 | 
| coe |  3 | 14000 | 
| igbm |  4 | 15000 | 
| igbm |  5 | 21000 | 
| igbm |  6 | 31000 | 
+--------+-------+--------+ 

Table2 
+-------+------+ 
| empid | name | 
+-------+------+ 
|  1 | a | 
|  2 | b | 
|  3 | c | 
|  4 | d | 
|  5 | e | 
|  6 | f | 
+-------+------+ 

average salary 
+--------+-------------+ 
| deptid | avg(salary) | 
+--------+-------------+ 
| coe | 15333.3333 | 
| igbm | 22333.3333 | 
+--------+-------------+ 

I need who got more than avg(salary) in deptid wise 

| deptid | empid | salary | name  | 
+--------+-------+--------+----------+ 
| coe |  1 | 19000 | a  | 
| igbm |  6 | 31000 | f  | 


select a.deptid, a.empid, a.salary, b.name from Table1 a, Table2 b where a.empid= b.empid and salary>(select avg(salary) from Table1) group by deptid ; 


I used this query it's not working 

+--------+-------+--------+----------+ 
| deptid | empid | salary | name  | 
+--------+-------+--------+----------+ 
| coe |  1 | 19000 | a  | 
| igbm |  5 | 21000 | e  | 
+--------+-------+--------+----------+ 


select a.deptid, a.empid, a.salary, b.name from Table1 a, Table 2 where a.empid= b.empid and salary>(select avg(salary) from Table1 order by deptid); 

+--------+-------+--------+----------+ 
| deptid | empid | salary | name  | 
+--------+-------+--------+----------+ 
| coe |  1 | 19000 | a   | 
| igbm |  5 | 21000 | e   | 
| igbm |  6 | 31000 | f   | 
+--------+-------+--------+----------+ 

我使用此查詢,這是採取整體平均不明智的。

+0

select a.deptid, a.empid, a.salary, b.name from Table1 a, Table2 b where a.empid= b.empid and a.salary>( select avg(salary) from Table1 c where c.deptid = a.deptid ) 

範例這個我稱之爲藝術;-) – Martin

+0

你熟悉的having子句組和? –

+0

我還在學習 –

回答

3

你只需要取平均值的部門,不是所有:在SQL Fiddle

+0

祝賀您完成作業 – Strawberry

+0

非常感謝您先生 –