简体   繁体   中英

How to select sum(max remain(x+y+z)) from MySQL, to catch sum(1200+1300+1400)

How to select sum(max remain(x + y + z)) from MySQL, to catch sum(1200+1300+1400) ?

id | user | remain
-----------------
1  | x   | 1000
----------------
2  | x   | 1200
----------------
3  | y   | 1100
----------------
4  | y   | 1300
----------------
5  | z   | 1200
----------------
5  | z   | 1400
----------------
using (SqlConnection cn = new SqlConnection(Class1.x))
        {
            cn.Open();
            string cm1 = "select sum(max remain(all users)) as 'total' from item_new_company";
            using (SqlCommand cmd = new SqlCommand(cm1, cn))
            {
                using (SqlDataReader dr = cmd.ExecuteReader())
                { dr.Read(); tot5 = dr["total"].ToString(); }
            }
        }

Like this:

SELECT SUM(MaxRemain) TotalOfMaxRemains
FROM
(
    SELECT MAX(remain) AS MaxRemain
    FROM item_new_company
    GROUP BY user
) AS t;

SQL Fiddle Demo

The result:

| TOTALOFMAXREMAINS |
---------------------
|              3900 |

The subquery:

SELECT MAX(remain) AS MaxRemain
FROM item_new_company
GROUP BY user

with GROUP BY user and MAX(remain) , will give you the max of remain for each user , then in the outer query the SUM will give you the total.


Update

For SQL Server, the previous query should work fine, but there is another way to do so:

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;

SQL Fiddle Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM