我正在尝试构建一个查询,显示聚合列中值最高的行“NumberOfArticles”。但是,由于有多个行具有相同的最高值,因此我不确定如何正确限制查询生成的行数。
SELECT WRT_ID, COUNT(ART_ID) AS NumberOfArticles
FROM Articles
GROUP BY WRT_ID
ORDER BY NumberOfArticles DESC
答案 0 :(得分:1)
我认为这对你来说已经足够了
SELECT WRT_ID, max(ART_ID) AS NumberOfArticles
FROM Articles
GROUP BY NumberOfArticles
ORDER BY NumberOfArticles DESC
答案 1 :(得分:1)
SELECT TOP 1 WRT_ID, COUNT(ART_ID) AS NumberOfArticles
FROM Articles
GROUP BY WRT_ID
ORDER BY 2 DESC
如果有多个NumberOfArticles计数最高的行,则会包含关系。如果您不希望包含绑定,但只有一个具有最高NumberOfArticles计数的绑定,请将GROUP BY放在子查询中并根据需要更改ORDER BY。
SELECT TOP 1 sub.WRT_ID, sub.NumberOfArticles
FROM (
SELECT WRT_ID, COUNT(ART_ID) AS NumberOfArticles
FROM Articles
GROUP BY WRT_ID
) AS sub
ORDER BY 2 DESC, 1 DESC;
答案 2 :(得分:0)
我想你可能想要:
SELECT A.WRT_ID, (SELECT MAX(B.ART_ID) FROM Articles As B WHERE B.WRT_ID = A.WRT_ID) As NumberOfArticles
FROM Articles A
ORDER BY 2 Desc
这使用子选择来获得每个Wrt_Id
的最高Art_Id我看到你在你的样本中使用了COUNT,虽然问题提示更多的是最大值,但如果它是计数,那么你只需修改为:
SELECT A.WRT_ID, (SELECT COUNT(B.ART_ID) FROM Articles As B WHERE B.WRT_ID = A.WRT_ID) As NumberOfArticles
FROM Articles A
ORDER BY 2 Desc
答案 3 :(得分:0)
SELECT WRT_ID, COUNT(ART_ID) AS NumberOfArticles
FROM Articles
GROUP BY WRT_ID
HAVING COUNT(ART_ID)=(SELECT MAX(t.c) FROM ( SELECT WRT_ID,COUNT(ART_ID) AS c
FROM Articles GROUP BY WRT_ID ) t )
ORDER BY NumberOfArticles DESC
这为您提供了所有最大行数。