SQL如何使用内部查询正确组合MAX和COUNT

时间:2019-03-02 17:58:59

标签: sql sql-server tsql count max

我在从 ProblemsAmount 列中仅选择具有最大值的行时遇到了问题,该列表示内部查询中的COUNT(*)。看起来像:

PersonID   | PersonName   | ProblemID   | ProblemsAmount
1          | Johny        | 1           | 10
1          | Johny        | 2           | 5
1          | Johny        | 3           | 18
2          | Sara         | 4           | 2
2          | Sara         | 5           | 12
3          | Katerina     | 6           | 17
3          | Katerina     | 7           | 2
4          | Elon         | 8           | 20
5          | Willy        | 9           | 6
5          | Willy        | 10          | 2

我想要得到什么:

PersonID   | PersonName   | ProblemID   | ProblemsAmount
1          | Johny        | 3           | 18
2          | Sara         | 5           | 12
3          | Katerina     | 6           | 17
4          | Elon         | 8           | 20
5          | Willy        | 9           | 6

我现在拥有的代码:

SELECT A.PersonID,
       A.PersonName,
       A.ProblemID,
       MAX(A.ProblemsCounter) AS ProblemsAmount
FROM (SELECT Person.PersonId AS PersonID,
             Person.Name AS PersonName,
             Problem.ProblemId AS ProblemID,
             COUNT(*)      AS ProblemsCounter
      FROM Person,
           Problem
      WHERE Problem.ProblemId = Person.ProblemId
      GROUP BY Person.PersonId, Person.Name, Problem.ProblemId
     ) A
GROUP BY A.PersonID, A.PersonName, A.ProblemID
ORDER BY A.PersonName, ProblemsAmount DESC;

内部查询返回与外部查询相同的内容,我对MAX函数感到困惑。它不起作用,我也不明白为什么。我尝试使用HAVING进行修复,但未成功。

谢谢。

2 个答案:

答案 0 :(得分:5)

TOP (1) WITH TIESROW_NUMBER()是不需要子查询的简单方法:

SELECT TOP (1) WITH TIES p.PersonId, p.Name AS PersonName,
       pr.ProblemId, COUNT(*) AS ProblemsCounter
FROM Person p JOIN
     Problem pr
     ON pr.ProblemId = p.ProblemId
GROUP BY p.PersonId, p.Name, pr.ProblemId
ORDER BY ROW_NUMBER() OVER (PARTITION BY p.PersonId ORDER BY COUNT(*) DESC);

请注意,我还修复了JOIN语法。 始终使用正确的,明确的,标准 JOIN语法。

答案 1 :(得分:1)

不需要子查询,请尝试如下操作,并避免逗号分隔的联接

 SELECT          Person.PersonID , 
                 Person.Name AS PersonName,
                 COUNT(Problem.ProblemId)  AS ProblemsCounter
                 ,max(ProblemsAmount) as ProblemsAmount
          FROM Person left join
               Problem
          on Problem.ProblemId = Person.ProblemId
          GROUP BY Person.PersonID, Person.Name