I cant manage to come up with a query for a problem. I have three tables
CREATE TABLE institute (
iid INT PRIMARY KEY,
sign VARCHAR(127) UNIQUE,
city VARCHAR(127) NOT NULL,
area INT CHECK (area>0));
CREATE TABLE desease (
did INT PRIMARY KEY,
name VARCHAR(127) UNIQUE,
level INT CHECK (level>0));
CREATE TABLE studies (
did INT,
iid INT,
FOREIGN KEY (did) REFERENCES desease (did),
FOREIGN KEY (iid) REFERENCES institute (iid),
PRIMARY KEY (iid,did));
My question is: What are the names of the deseases by the largest number of institutes from Lisbon (Lisbon beeng the city
from institute
). This is what i came up with but it doesnt give me the right answer.
SELECT DISTINCT D.name, MAX(I.iid)
FROM desease D, studies S
JOIN institute I ON (S.iid = I.iid)
WHERE I.city = 'Lisboa' AND D.did = S.did
GROUP BY D.nome
HAVING COUNT(I.iid) = MAX(I.city)
As an example : Imagine 5 institutes al with city = 'Lisbon' and with iid A,B,C,D,E respectevely (just for demonstration purposes, I know type is INT); 5 Diseases with name = Z,X,N,V,M respectevely.
Now lets say desease Z,X, and M are studied by institutes A,B,C (in any order), desease N is studied by D(1 inst.) and desease V is studied by E (only one). So the max number of deseases studied by any Lisbon institute is 3 (A,B and C all study 3 deseases) so the table would look like this
Z - 3
X - 3
M - 3
Edit : I managed to found a way to do it. Here is the query that I came up with
SELECT DISTINCT D.name, COUNT(*) AS C
FROM desease D, studies E, institute I
WHERE I.iid = E.iid AND D.did = E.did AND I.city = "Lisboa"
GROUP BY D.name
HAVING C >= ALL (
SELECT COUNT(*)
FROM desease D, studies E, institute I
WHERE I.iid = E.iid AND D.did = E.did AND I.cidade = "Lisboa"
GROUP BY D.name
);