简体   繁体   中英

How to select records with two columns matching values in one table?

I am creating one request form online, where employee generate request in system but his/her boss only able to view those employee's request who are working under him.

For ex: In an organization there are various employees are working under 1 boss.

---------------------
|EmpNo   |BossNo    |
---------------------
|011     |001       |
|012     |001       |
|013     |001       |
|014     |002       |
---------------------

Here in above table scenario if an employee(012) will generate any request then only boss(001) is able to view that request no one else, same as employee(014) will generate any request then only boss(002) is able to view that request and accept it.

I want to create SQL Query for this..But I am fail to create query for this. Here below is the query

select e1.empno, e1.bossno
  from employeedetails as e1
  inner join employeedetails as e2
    on e1.empno= e2.empno
   and e1.bossno= e2.bossno
  group by e1.empno, e1.bossno
  order by e1.empno, e1.bossno

Because, both table retrieve same values then use join as e1.empno= e2.empno and e1.bossno= e2.bossno

I think so:

select e1AsBoss.empno as idBoss , e2AsEmployer.empno as idEmployer
  from employeedetails as e1AsBoss
  inner join employeedetails as e2AsEmployer
    on e1AsBoss.empno= e2AsEmployer.bossno
  group by e1AsBoss.empno, e2AsEmployer.empno
  order by e1AsBoss.empno, e2AsEmployer.empno

Something like this:

SELECT request.Info, request.empno, empDetails.EmployeeName
FROM requestTable as Request
    INNER JOIN employeedetails AS empDetails ON Request.empno = empDetails.empno
WHERE empDetails.bossno = @IdOfLoggedInEmployee

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