简体   繁体   中英

SQL retrieve column from another row in same table

I'm trying to build a query that will retrieve employee information from a table that also contains a column named "REPORTS_TO" which is the value of another field called POSITION_NBR (essentially both employees and managers are all in this same table) So I would like to retrieve a row of employee data and then on one of the columns in that row pull in their manager's name which is referenced in another row in the same table.

As an example, employee John Smith has a row with "POSITION_NBR" equal to '1234' and also the column "REPORTS_TO" equal to "5678" On another row, his manager Susie Snowflake has her unique row in the same table with the "POSITION_NBR" equal to "5678" (Same as the "REPORTS_TO" value in the other row). Many employees can share the same manager, and manager's also have a manager.

It's a simple query where I'm doing a LEFT OUTER JOIN on the same table with a different alias. I'm getting inconsistent data being resulted, this is the query I am using:

SELECT 
 A.COMPANY,
 A.DEPTID,
 A.DEPTNAME, 
 A.LOCATION, 
 A.NAME, 
 A.EMPLID, 
 A.REG_TEMP, 
 A.FULL_PART_TIME, 
 A.JOBCODE, 
 A.JOBTITLE, 
 A.SERVICE_DT, 
 A.TERMINATION_DT, 
 A.POSITION_NBR, 
 A.EMPL_STATUS, 
 A.REPORTS_TO,
 AA.NAME AS MANAGER_NAME
FROM PS_EMPLOYEES A
 LEFT OUTER JOIN PS_EMPLOYEES AA ON AA.POSITION_NBR = A.REPORTS_TO 
--AND AA.EMPLID = A.EMPLID 

If I remove the un-commented code (to make it active) on the last line I get the correct number of rows, however the last column (AA.NAME AS MANAGER NAME) has all NULL values on every row (should not have any nulls as all employees have a manager assigned). If I keep this line commented out (as written below) then I get about 2,700 additional rows in my results (employee's are duplicated with different manager names)

Any help is appreciated, thanks!

The format of your query - without the commented part - is correct, and I believe @Gordon_Linoff is correct in that there are duplicate POSITION_NBR values present and this is why you are getting the additional rows.

It doesn't make sense to add in the AND AA.EMPLID = A.EMPLID condition because this joins each employee to themselves so you get NULLS for the manager, unless they are their own manager!

Your description would lead me to suspect that position_nbr is duplicated. Can you try this?

select position_nbr, count(*) as cnt
from ps_employees
group by position_nbr
having count(*) > 1;

You have to left join against the same table.

SELECT
 A.NAME
 A.POSITION_NBR
 A.REPORTS_TO
 B.NAME as 'MANAGER'
FROM
 PS_EMPLOYEES A
LEFT JOIN (SELECT NAME, POSITION_NBR FROM PS_EMPLOYEES) B ON B.POSITION_NBR = A.REPORTS_TO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM