SQL使用2个表获得最大计数

时间:2017-12-02 15:56:47

标签: sql count

我有2个表Specialization,我将其称为table(id,Spec)和Personal,我称之为table2(id,first_name)

我想要做的是在表中计算每个id在那里显示的次数(我在内部循环中执行此操作)然后我想要做的是,从table2显示具有最大计数的id的名称

SELECT 
    MAX(subQuery.idCount) AS MaxCount, subQuery.first_name
FROM
    (SELECT 
         COUNT(Table.Specialty) AS idCount
     FROM 
         Specialization as Table, Personal as Table2
     GROUP BY
         Table.ID) AS subQuery
GROUP BY 
    subQuery.Did

我做错了什么?

2 个答案:

答案 0 :(得分:0)

你可能需要这样的东西。

WITH cte (Id,IdCount)   AS
      SELECT 
    (  SELECT  ID, 
             COUNT(Specialty) AS IdCount
         FROM 
             Specialization 
         GROUP BY
             ID   )
  select first_name,idCount as MaxCount 
      FROM 
      (
        SELECT per.first_name , idCount , 
            row_number () OVER ( ORDER BY idCount DESC )  rn FROM 
        cte c JOIN Personal per ON c.id = per.id
   ) where rn = 1;

答案 1 :(得分:0)

首先,看看你的子查询:

SELECT 
    COUNT(Table.Specialty) AS idCount
FROM 
    Specialization as Table, Personal as Table2
GROUP BY
    Table.ID

您只返回一列idCount,但稍后,您尝试按subQuery.Did进行分组,您无需在任何地方进行分组。您也不会在任何地方过滤或公开Table2,因此不需要它。如果您的子查询类似于:

,则可以修复此问题
SELECT 
    Specialization.ID, COUNT(Specialization.Specialty) AS idCount
FROM 
    Specialization
GROUP BY
    Specialization.ID

然后,在主查询中选择的列中,您尝试显示subQuery.first_name,子查询也不会显示该specialty。但是,现在您的id数量为Personal,您可以使用first_name进行内部联接,以获取每个id的{​​{1}}:< / p>

SELECT 
    subQuery.idCount, Personal.first_name
FROM  
    (SELECT 
        Specialization.ID, COUNT(Specialization.Specialty) AS idCount
    FROM 
        Specialization
    GROUP BY
        Specialization.ID) AS subQuery
INNER JOIN 
    Personal ON Personal.ID = subQuery.ID

然后,这只是按计数排序并获取第一行的问题,第一行的语法略有不同,具体取决于您使用的SQL系统。例如,在SQL Server中:

SELECT TOP 1
    subQuery.idCount, Personal.first_name
FROM  
    (SELECT 
        Specialization.ID, COUNT(Specialization.Specialty) AS idCount
    FROM 
        Specialization
    GROUP BY
        Specialization.ID) AS subQuery
INNER JOIN 
    Personal ON Personal.ID = subQuery.ID
ORDER BY subQuery.idCount desc

但是,这可以在没有子查询的情况下完成,并避免旧式连接,例如@marc_s在问题上发表评论。

使用PersonalSpecialization之间的内部联接,使用ID作为关系,Specialization中的所有行都包含first_name的额外行每个。然后,您可以按first_name分组以获取每个名称的行数(特化)。

SELECT COUNT(*), Personal.first_name
FROM Personal 
INNER JOIN Specialization ON Specialization.id = Personal.id
GROUP BY Personal.first_name

然后,您可以按计数订购并仅返回第一行。