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
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
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
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With