简体   繁体   中英

SQL Query to lookup on same table from which selecting the records

Sample records :

Custid pref_location
C1     PUNE
C1     MUMBAI
c1     DELHI    
C2     PUNE
C2     MUMBAI
C3     MUMBAI  
c4     PUNE
C5     DELHI

I want to fetch records where pref location is only PUNE or MUMBAI .I am doing it with help of below query :

SELECT *
FROM EMP_PRE_LOCATION E1
WHERE EXISTS (SELECT 1 
        FROM EMP_PRE_LOCATION E2 
        WHERE E2.EID=E1.EID AND E2.PRE_LOCATION in ('PUNE','MUMBAI'))
AND NOT  EXISTS (SELECT 1 
        FROM EMP_PRE_LOCATION E3 
        WHERE E3.EID=E1.EID AND E3.PRE_LOCATION NOT in('PUNE','MUMBAI'));

Is their any better way to achieve the same ?

I think you simply want:

SELECT E1.*
FROM EMP_PRE_LOCATION E1
WHERE NOT EXISTS (SELECT 1 
                  FROM EMP_PRE_LOCATION E2 
                  WHERE E2.EID = E1.EID AND
                        E2.PRE_LOCATION NOT IN ('PUNE', 'MUMBAI')
                 );

If you just want employees in only those two locations, then you can use GROUP BY and HAVING :

SELECT E1.EID
FROM EMP_PRE_LOCATION E1
GROUP BY E1.EID
HAVING SUM(CASE WHEN E1.PRE_LOCATION NOT IN ('PUNE', 'MUMBAI') THEN 1 ELSE 0 END) = 0;

You can add LISTAGG(E1.PRE_LOCATION, ',') if you want a list of the locations.

Please try this.

SELECT *
FROM EMP_PRE_LOCATION
WHERE pref_location ='PUNE' OR pref_location ='MUMBAI'

Second WHERE clause would do the you want :

SELECT E1.*
FROM EMP_PRE_LOCATION E1
WHERE E1.PRE_LOCATION IN ('PUNE','MUMBAI') AND 
      NOT EXISTS (SELECT 1 
                  FROM EMP_PRE_LOCATION E3 
                  WHERE E3.EID = E1.EID AND E3.PRE_LOCATION NOT IN ('PUNE','MUMBAI')
                 );

This would return only EID s which have only LOCATION IN ('PUNE','MUMBAI') .

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