![](/img/trans.png)
[英]Get the all of the entries from a mysql table where there version is the highest for there ID
[英]How to get the id of highest total from all groups? (MySQL)
假設我有下表
id Salary 1 5 2 3 1 3 1 6 2 5 3 5 3 2 4 1 4 3 2 9
我想從所有組中獲得最高總薪水的ID。 在這種情況下,結果應為id = 2 sum = 17(即3 + 5 + 9 = 17)
如果您真的只希望/需要一個id
組,那么使用LIMIT
可能是這里最簡單的方法:
SELECT id, SUM(Salary) AS total
FROM yourTable
GROUP BY id
ORDER BY SUM(Salary) DESC
LIMIT 1;
如果可以為最高薪水建立聯系,那么我們將需要做更多的工作。 在MySQL 8+之前,@ MKhalid給出的查詢是我們需要做的。 從MySQL 8+開始,我們可以使用RANK
分析功能:
SELECT id, total
FROM
(
SELECT id, SUM(Salary) AS total,
RANK() OVER (ORDER BY SUM(salary) DESC) rank
FROM yourTable
GROUP BY id
) t
WHERE rank = 1;
使用CTEName AS(從testTable GROUP BY id中選擇SELECT ID,SUM(salary)作為total_salary)從CTEName ORDER BY BY total_salary desc中選擇前1個ID
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.