我一直在使用HansUp给我的以下代码(干杯!),它一直很好用:
SELECT g.ID, Count(t.Grade) AS Total
FROM grade AS g
LEFT JOIN (SELECT Grade FROM telephony WHERE [Date] BETWEEN #08/16/2010# AND #08/20/2010#) AS t ON g.ID=t.Grade
GROUP BY g.ID
ORDER BY 2 DESC;
我现在正在寻找返回的TOP 5结果。我认为它会如此简单:
SELECT **TOP 5** g.ID, Count(t.Grade) AS Total
FROM grade AS g
LEFT JOIN (SELECT Grade FROM telephony WHERE [Date] BETWEEN #08/16/2010# AND #08/20/2010#) AS t ON g.ID=t.Grade
GROUP BY g.ID
ORDER BY 2 DESC;
不幸的是,这不起作用。
有没有人有任何想法。
由于
答案 0 :(得分:3)
TOP子句将根据您的第一个排序字段为您提供顶级。由于您的第一个排序字段是所有记录的常量(2),因此您将获得所有记录。将ID字段添加到ORDER BY子句中,您将只获得五个记录。
SELECT TOP 5 g.ID, Count(t.Grade) AS Total
FROM grade AS g LEFT JOIN (SELECT Grade FROM telephony WHERE [Date] BETWEEN #08/16/2010# AND #08/20/2010#) AS t ON g.ID = t.Grade
GROUP BY g.ID
ORDER BY g.ID, 2 DESC;
如果您实际上按降序排在前5位,请将SQL更改为以下内容:
SELECT TOP 5 g.ID, Count(t.Grade) AS Total
FROM grade AS g LEFT JOIN (SELECT Grade FROM telephony WHERE [Date] BETWEEN #08/16/2010# AND #08/20/2010#) AS t ON g.ID = t.Grade
GROUP BY g.ID
ORDER BY Count(t.Grade) DESC , 2 DESC;
这是最重要的值,因此如果多个记录的总数相同且恰好位于Total的前5个值中,那么您将全部返回。如果你真的只想要五条记录,你必须对一个独特的字段进行排序。
答案 1 :(得分:0)
这应该有用。
SELECT TOP 5 g.ID, Count(t.Grade) AS Total
FROM grade AS g
LEFT JOIN (SELECT Grade FROM telephony WHERE [Date] BETWEEN #08/16/2010# AND #08/20/2010#) AS t ON g.ID=t.Grade
GROUP BY g.ID
ORDER BY 2 DESC
答案 2 :(得分:0)
据我所知,这应该有效:
SELECT TOP 5 g.ID, Count(t.Grade) AS Total
FROM grade AS g
LEFT JOIN (SELECT Grade FROM telephony WHERE [Date] BETWEEN #08/16/2010# AND #08/20/2010#) AS t ON g.ID=t.Grade
GROUP BY g.ID
ORDER BY Count(t.Grade) DESC;
这里的关键点是,当您想在WHERE或ORDER BY子句中使用它时,可以使用SELECT语句中的完整表达式。
如果您只是使用Access查询网格来编写SQL,那么您可以立即获得正确的结果(尽管您必须深入SQL视图来编写子查询)。