Like this:
SELECT SUM(MaxRemain) TotalOfMaxRemains FROM ( SELECT MAX(remain) AS MaxRemain FROM item_new_company GROUP BY user ) AS t;
Result:
| TOTALOFMAXREMAINS | --------------------- | 3900 |
Subquery:
SELECT MAX(remain) AS MaxRemain FROM item_new_company GROUP BY user
with GROUP BY user and MAX(remain) , will give you the maximum remain for each user , then in the external query, SUM will give you the total.
Update
For SQL Server, the previous query should work fine, but there is another way:
WITH CTE AS ( SELECT *, ROW_NUMBER() OVER(PARTITION BY [user] ORDER BY id DESC) AS rownum FROM item_new_company ) SELECT SUM(remain) AS Total FROM CTE WHERE rownum = 1;
source share