SQL查询 - 计数 - 最大

时间:2011-11-29 20:57:05

标签: sql join count max

我无法设法查询问题。我有三张桌子

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));

我的问题是:来自里斯本(里斯本的city来自institute)的研究所数量最多的是什么?这是我提出的,但它没有给我正确的答案。

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)

作为一个例子:想象5个机构al = city ='Lisbon'和iid A,B,C,D,E(仅用于演示目的,我知道类型是INT); 5名疾病的名称分别为Z,X,N,V,M。

现在假设研究A,B,C(任何顺序)研究Z,X和M,研究D由D(1 inst。)研究,desease V由E研究(仅1) 。因此,任何里斯本研究所研究的最大疾病数量是3(A,B和C所有研究3个疾病)所以表格看起来像这样

Z - 3
X - 3
M - 3

编辑:我设法找到了办法。这是我提出的查询

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

);

3 个答案:

答案 0 :(得分:0)

我不太了解结构/问题,但我确实看到你正在混合连接并且有一个交叉连接会增加记录的数量。

SELECT DISTINCT D.name, MAX(I.iid)
FROM desease D
INNER JOIN  studies S ON D.iid=S.Did
INNER 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)

答案 1 :(得分:0)

粗略猜测你需要什么:

SELECT stu.iid, COUNT(*) AS nstudies
FROM studies stu, institute ins
WHERE stu.iid=ins.iid
AND ins.city='Lisboa'
GROUP BY stu.iid
ORDER BY nstudies DESC;

这应该会给你一份里斯本学院的名单和他们所做的研究数量。

SELECT stu.did, COUNT(*) AS ninst
FROM studies stu, institute ins, disease dis
WHERE stu.iid=ins.iid
AND stu.did=dis.did
AND ins.city='Lisboa'
GROUP BY stu.did
ORDER BY ninst DESC;

这会给你一个desease列表和Lisboa instutitues的数量。

不幸的是,你的问题为你需要的东西留下了很大的空间 - 也许你应该添加一些示例数据和预期的结果。

答案 2 :(得分:0)

这将返回一份在里斯本拥有一所研究所的疾病名单,从里斯本研究所数量最多的研究所开始,并将其下降:

SELECT D.name, COUNT(*) as numberOfInstitutes
FROM desease D
INNER JOIN studies S ON D.did=S.did
INNER JOIN institute I ON (S.iid = I.iid)
WHERE I.city = 'Lisbon'
GROUP BY D.did
ORDER BY COUNT(*) desc

如果您只需要具有最多机构的那个并且您需要desease表中的其余列,则可以执行此操作(在Sql Server中):

SELECT TOP 1 D.* 
FROM desease D
INNER JOIN
(
    SELECT D.did, COUNT(*) as numberOfInstitutes
    FROM desease D
    INNER JOIN studies S ON D.did=S.did
    INNER JOIN institute I ON (S.iid = I.iid)
    WHERE I.city = 'Lisbon'
    GROUP BY D.did
) as tblCount on tblCount.did = D.did
ORDER BY numberOfInstitutes desc