我正在嘗試構建一個查詢,以顯示聚合列「NumberOfArticles」中具有最高值的行。但是,由於有多行具有相同的最高值,因此我不確定如何正確限制查詢生成的行數。以最大聚合值顯示查詢結果
SELECT WRT_ID, COUNT(ART_ID) AS NumberOfArticles
FROM Articles
GROUP BY WRT_ID
ORDER BY NumberOfArticles DESC
我正在嘗試構建一個查詢,以顯示聚合列「NumberOfArticles」中具有最高值的行。但是,由於有多行具有相同的最高值,因此我不確定如何正確限制查詢生成的行數。以最大聚合值顯示查詢結果
SELECT WRT_ID, COUNT(ART_ID) AS NumberOfArticles
FROM Articles
GROUP BY WRT_ID
ORDER BY NumberOfArticles DESC
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;
我想你可能想:
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
它使用一個子選擇,以獲得最高Art_Id每個Wrt_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
我想這可能是夠你
SELECT WRT_ID, max(ART_ID) AS NumberOfArticles
FROM Articles
GROUP BY NumberOfArticles
ORDER BY NumberOfArticles DESC
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
這給你所有的最大行數。