Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Either in not both clause in select sql

Tags:

sql

oracle

Find the names of all departments located either in BOSTON or in DALLAS" and not in both cities.

I having the code like this

SELECT D.DNAME 
FROM DEPARTMENT D 
INNER JOIN DEPTLOC L ON L.DNAME = D.DNAME 
WHERE L.CITY='BOSTON' 
OR L.CITY='DALLAS' ;

But this will show the department that located in BOSTON OR DALLAS . But i just want either in, what should i put in order to get the result.

Example: in my DEPTLOC TABLE

     //DEPTLOC
     DNAME      CITY
     ----------------
     ACCOUNTING  BOSTON
     ACCOUNTING  DALLAS
     SALES       DALLAS
     TRANSPORT   BOSTON
     TRANSPORT   DALLAS

So in my DEPARTMENT i should get output like

      DNAME
      ----------
      SALES
like image 982
user3553846 Avatar asked Mar 20 '23 19:03

user3553846


2 Answers

Group them, then calculate the total count for each departments, then filter all departments which has only one location.

SELECT D.DNAME 
FROM DEPARTMENT D 
INNER JOIN DEPTLOC L ON L.DNAME = D.DNAME 
WHERE L.CITY='BOSTON' 
OR L.CITY='DALLAS'
GROUP BY
D.DNAME
HAVING COUNT(1) = 1
like image 98
Pred Avatar answered Mar 29 '23 18:03

Pred


You could write:

SELECT department.dname
  FROM department
  JOIN deptloc
    ON department.dname = deptloc.dname
 WHERE deptloc.city IN ('BOSTON', 'DALLAS')
 GROUP
    BY department.dname
HAVING COUNT(DISTINCT deptloc.city) = 1
;

For that matter, since each value in deptloc.dname presumably also occurs in department.name, you can dispense with the join and just write:

SELECT dname
  FROM deptloc
 WHERE city IN ('BOSTON', 'DALLAS')
 GROUP
    BY dname
HAVING COUNT(DISTINCT city) = 1
;
like image 31
ruakh Avatar answered Mar 29 '23 16:03

ruakh