Dan*_*hov 2 sql t-sql sql-server count max
我在选择问题列中只有最大值的行时遇到问题,该列代表内部查询中的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
Run Code Online (Sandbox Code Playgroud)
我想得到什么:
PersonID | PersonName | ProblemID | ProblemsAmount
1 | Johny | 3 | 18
2 | Sara | 5 | 12
3 | Katerina | 6 | 17
4 | Elon | 8 | 20
5 | Willy | 9 | 6
Run Code Online (Sandbox Code Playgroud)
我现在拥有的代码:
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;
Run Code Online (Sandbox Code Playgroud)
内部查询返回与外部查询相同的东西,我对MAX函数感到困惑。它不起作用,我也不明白为什么。我尝试使用HAVING进行修复,但未成功。
提前致谢。
一个不需要子查询的简单方法是TOP (1) WITH TIES和ROW_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);
Run Code Online (Sandbox Code Playgroud)
请注意,我还修复了JOIN语法。 始终使用正确,明确,标准的 JOIN语法。