mysql - 如何在SQL中计算 "as large as the next #"中的数字?

标签 mysql sql

假设我有一个表格,它只是一列中的数字列表,称为 Standing,按从大到小的顺序排列。我希望能够计算从第二行开始第一行等于多少行。

示例:

Americas army is as large as the next 10 combined.

这些是实际结果(超过 50k,因为总共有近 10k 个结果)。

1663255
287519
238346
197905
193162
166579
134234
113571
81250
69694
67342
65702
55770
55579
54339
54328
54247
51090

我知道如何以编程方式执行此操作,我只是计算一个循环,同时从第一个值中减去每个值,直到它为负数,但在 SQL 中很难执行此操作。

最佳答案

您需要一个累计金额。 。 。对于除第一行之外的所有行。这在 MySQL 中有点棘手,但您可以使用变量来做到这一点:

select count(*)
from (select t.*, (@sum := @sum + standing) as running_standing
      from t cross join
           (select @sum := 0) params
      where t.standing < (select max(t.standing) from t)
      order by t.standing desc
     ) tt cross join
     (select max(t.standing) as max_standing from t) as m
where tt.running_standing < m.max_standing;

关于mysql - 如何在SQL中计算 "as large as the next #"中的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46075158/

相关文章:

mysql - Laravel 5 插入带有外键错误的行

c# - 将命令文本转换为已回答问题中的字符串问题

mysql - 未找到方法 openMask P4A

java - 获取异常 java.sql.SQLException : socket creation error

mysql - 如何从组中选择所有行,直到出现值

sql - 如何使用 SQL 计算给定轨迹中每条边的行进次数?

mysql - 为什么我的数据库查询在所需列中返回零(无数据)

c# - 在 Dapper Multiple Results 中,当 where 子句取决于第一个查询的结果时,如何让第二行查询工作?

mysql - GROUP BY 每组的最大 count()

php - 保存搜索结果的数据库结构