简体   繁体   中英

Need Union kind of behavior without using Union of queries/resultset

I have two table one say Employee with columns as

EmpId Name Class Region
 1     rr    x     t
 2     tr    v     g 

Another table ConfidentalEmployee with columns as

EmpId(foreign key) Name
 1                  rr

Now have to write query with all the fields of Employee table but those Employee's Id is in ConfidentalEmployee table the details like ( Class, Region ) for such employee should come as CAN'T DISCLOSE as follows:

EmpId  Name    Class              Region
 1      rr    CAN'T DISCLOSE    CAN'T DISCLOSE
 2      tr       v                  g 

I can do it using two queries with join based on EMPIds and perform an union on both the resultset. My query is as follows:

select e.EmpId, e.Name,e.Class,e.Region from Employee e inner join ConfidentalEmployee ce on e.EmpId <> ce.EmpId
UNION
select e.EmpId, e.Name,'CAN'T DISCLOSE' as Class, 'CAN'T DISCLOSE' as Region from Employee e inner join ConfidentalEmployee ce on e.EmpId = ce.EmpId

But am wondering if its possible with a single query without union operation?

You can try this query

SELECT Emp.EmptId, Emp.Name,
       CASE WHEN CEmp.EmpId IS NULL THEN Emp.Class ELSE 'CAN''T DISCLOSE' END AS Class,
       CASE WHEN CEmp.EmpId IS NULL THEN Emp.Region ELSE 'CAN''T DISCLOSE' END AS Region 
FROM Employee AS Emp
LEFT JOIN ConfidentialEmployee CEmp ON Emp.EmpId = CEmp.EmpId

You want a join, specifically a left outer join and check for matches:

select e.EmpId, coalesce(ce.Name, e.Name) as Name,
       (case when ce.empid is not null then 'CAN''T DISCLOSE' else e.Class end) as class, 
       (case when ce.empid is not null then 'CAN''T DISCLOSE' else e.Region end) as region
from employee e left outer join
     confidentialemployee ce
     on e.empid = ce.empid;

This is assuming that confidential employees are in both tables, as in the example in your question. Otherwise, union all is the appropriate approach.

Why are you trying to avoid a UNION? This is what they are made for.

select EmpID
    , Name
    , Class
    , Region
from Employee
union all
select EmpID
    , Name
    , 'Can''t Disclose'
    , 'Can''t Disclose'
from ConfidentialEmployee
order by EmpID

If i understand your question right, i would suggest the following:

Left join ConfidentalEmployee on EmpId, in the select statement use CASEs to check if ConfidentalEmployee.EmpId is NULL and alias "CAN'T DISCLOSE" as Class and Region.

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