答案 0 :(得分:0)
以下是您的原始查询:
SELECT COUNT(HistoryOfVotersCollege.AuditorID) AS CountOfAuditorID, HistoryOfVotersCollege.AuditorID
FROM HistoryOfVotersCollege
GROUP BY HistoryOfVotersCollege.AuditorID
ORDER BY COUNT(HistoryOfVotersCollege.AuditorID) DESC; -- Query 1
SELECT AudQ1.AuditorID, AudQ1.CountOfAuditorID
FROM PresResult
WHERE AudQ1.CountOfAuditorID=(SELECT MAX(AudQ1.CountOfAuditorID) FROM AudQ1); -- Query 2
您可以使用表别名(在本例中为" h")。这允许您声明您所引用的列来自表" h"而不是使用" HistoryOfVotersCollege"。
SELECT h.AuditorID, COUNT(h.AuditorID) as count -- Query 1
FROM HistoryOfVotersCollege h
GROUP BY h.AuditorID
ORDER BY count DESC;
对于下一位,您可以使用子查询来创建"派生表",这基本上是一个临时表。如果您的表格很大或查询未经优化,它可能会减慢查询速度,但它们也非常有用。
SELECT der.AuditorID, der.count FROM (
SELECT h.AuditorID, COUNT(h.AuditorID) as count -- Query 1
FROM HistoryOfVotersCollege h
GROUP BY h.AuditorID) der -- this is my derived table's alias, so i can call a column by using der.AuditorID for example
join (
SELECT h.AuditorID, COUNT(h.AuditorID) as count
FROM HistoryOfVotersCollege h
GROUP BY h.AuditorID
ORDER BY count desc
LIMIT 1 -- this is the highest count for any auditor
) der2 on der.count=der2.count;
这可能会很慢,但它是您问题的答案(因为它是一个连接,并使用一个查询的结果集加入另一个查询)。
这将为您提供所有HistoryOfVotersCollege.AuditorID
个与ID最高的人匹配的ID。
如果您只需要编号最高的人,您可以使用:
SELECT h.AuditorID, COUNT(h.AuditorID) as count -- Query 1
FROM HistoryOfVotersCollege h
GROUP BY h.AuditorID
ORDER BY count desc
LIMIT 1;