Jump to content

Recommended Posts

Hi all,

 

I've got the following two tables schemas:

 

emp(EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO), primary key is EMPNO

dept(DEPTNO, DNAME), primary key is DEPTNO

 

DEPTNO is a foreign key in the Emp table.

 

Anyway, the query is to find employees whose salary is greater than the average salary in their department.

 

I've got a view created called empd(EMPNO, ENAME, JOB, SAL, COMM, DNAME).

 

The answer for this query from my teacher is this:

 

SELECT e1.ename, e1. dname, e1.sal FROM empd e1 where e1. sal > (SELECT avg(sal)

FROM emp where e1.dname = dname)

 

I have tried this query on the database and it does work, but I don't understand why it should work. In the inner query, I am assuming that "sal" and "dname" are columns of emp? If "dname" is an attribute of the emp table than the query makes sense, but it is not an attribute, so why does this query work?

 

(I have sent an email to my teacher asking this but he hasn't replied and I've got a test tomorrow  :()

 

 

Link to comment
https://forums.phpfreaks.com/topic/67645-dont-understand-this-query/
Share on other sites

You are selecting from the view, empd, which does have a DNAME col

 

I'd do this

SELECT e1.ename, d1.dname, e1.sal
FROM emp e1
INNER JOIN dept d1 ON e1.deptno = d1.deptno
INNER JOIN (SELECT deptno, AVG(sal) as avsal FROM emp GROUP BY deptno) as X
  ON e1.deptno = X.deptno
WHERE e1.sal > X.avsal

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.