聚合MAX COUNT子查询,带连接

时间:2016-03-27 11:50:21

标签: mysql sql join

我有以下查询要解决:

“列出1990年及以后出生的会员,并组织了从实验室共同工作最多的项目获得资金的黑客马拉松。”

SELECT Member.email, Member.firstName, Member.lastName, Member.dateOfBirth, 
Hubs.organiserMember, MAX(LabInProject.projectID)
FROM LabInProject 
INNER JOIN Project ON LabInProject.projectID=Project.projectID 
INNER JOIN Hackathon ON Project.projectID=Hackathon.fundingProject 
INNER JOIN Hubs ON Hackathon.eventID=Hubs.eventID 
INNER JOIN Member ON Member.email=Hubs.organiserMember 
WHERE LabInProject.projectID = (SELECT MAX(LabInProject.projectID) FROM LabInProject) 
GROUP BY Hubs.organiserMember 
HAVING Member.dateOfBirth > '1990' 

SELECT MAX为我提供了行中最高的projectID(数字),而不是projectID的最高COUNT。

如何在表格中获得projectID的“MAX COUNT”:LabInProject?

我尝试使用派生表创建一个子查询:totalCount,但我不知道如何将它与连接连接起来,它不起作用。

HAVING  COUNT(*) =
(
  SELECT  COUNT(projectID) totalCount
  FROM    LabInProject 
  GROUP   BY projectID  
  LIMIT 1  
)

2 个答案:

答案 0 :(得分:0)

WHERE LabInProject.projectID = (SELECT MAX(LabInProject.projectID) FROM LabInProject) 

这里有一个语法错误。 尝试在声明的末尾发布结束括号。

答案 1 :(得分:0)

在内部联接中考虑下面的派生表,使用自己的派生表来替换早期的WHERE条件。这应该返回多个共享相同最大计数的项目:

...
INNER JOIN
   -- OBTAIN PROJECT AND COUNTS CONDITIONED TO THE MAX 
   (SELECT sub.ProjectID, Count(*) As ProjectIDCount
    FROM LabInProject sub
    INNER JOIN Project ON LabInProject.projectID=Project.projectID 
    INNER JOIN Hackathon ON Project.projectID=Hackathon.fundingProject 
    INNER JOIN Hubs ON Hackathon.eventID=Hubs.eventID 
    INNER JOIN Member ON Member.email=Hubs.organiserMember 
    WHERE Member.dateOfBirth > '1990' 
    GROUP BY sub.ProjectID
    HAVING Count(*) IN
       -- OBTAIN SCALAR VALUE OF MAX PROJECT COUNT
       (SELECT Max(dT.ProjectIDCount) As MaxOfProjectIDCount
        FROM
          -- OBTAIN PROJECT COUNTS
          (SELECT subdT.ProjectID, Count(*) As ProjectIDCount
           FROM LabInProject subdT
           INNER JOIN Project ON LabInProject.projectID=Project.projectID 
           INNER JOIN Hackathon ON Project.projectID=Hackathon.fundingProject 
           INNER JOIN Hubs ON Hackathon.eventID=Hubs.eventID 
           INNER JOIN Member ON Member.email=Hubs.organiserMember 
           WHERE Member.dateOfBirth > '1990'
           GROUP BY subdT.ProjectID) As dT)
   ) As temp
ON LabInProject.projectID = temp.projectID
...