简体   繁体   English

如何从MySQL中选择总和(最大剩余(x + y + z))以捕获总和(1200 + 1300 + 1400)

[英]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) ? 如何sum(max remain(x + y + z)) from MySQL中选择sum(max remain(x + y + z)) from ,以捕获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 SQL小提琴演示

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. 使用GROUP BY userMAX(remain) ,将为您提供每个userremain最大值,然后在外部查询中, SUM将为您提供总数。


Update 更新资料

For SQL Server, the previous query should work fine, but there is another way to do so: 对于SQL Server,以前的查询应该可以正常工作,但是还有另一种方法:

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 SQL小提琴演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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