要选择的 SQL 查询,直到 SUM(users_count) 达到 1000

A SQL query to select until SUM(users_count) reaches 1000(要选择的 SQL 查询,直到 SUM(users_count) 达到 1000)
本文介绍了要选择的 SQL 查询,直到 SUM(users_count) 达到 1000的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个 sql 查询来从我的消息队列中选择行,直到 SUM(users_count) 最多达到 1000.但是如果只返回一行并且该行的 users_count 为大于 1000.

I need a sql query to select rows from my messages queue, until SUM(users_count) reaches at most 1000. BUT there is no problem if there be only one row returned and that row's users_count is greater than 1000.

我需要类似的东西:(我添加了自己的关键字)

I need something like: (i added my own keywords)

SELECT * FROM `messages_queue` UNTIL SUM(users_count) < 1000 AT LEAST 1 ROW

这是我的表结构:

messages_queue
- msg_id
- msg_body
- users_count(消息接收者的数量)
- 时间(插入时间)

messages_queue
- msg_id
- msg_body
- users_count (number of message recieptors)
- time (insert time)

推荐答案

这个方案会进行累加,当总和超过1000时停止:

This solution will perform a cumulative sum, stopping when the sum exceeds 1000:

SELECT NULL AS users_count, NULL AS total
  FROM dual
 WHERE (@total := 0)
 UNION
SELECT users_count, @total := @total + users_count AS total
  FROM messages_queue
 WHERE @total < 1000;

这意味着如果你有两个值,比如 800,总和将是 1600.第一个 SELECT 只是初始化 @total 变量.

That means that if you have two values of, say, 800, the sum total will be 1600. The first SELECT is just to initialise the @total variable.

如果你想防止总和超过 1000,除了单行的值大于 1000 的情况外,我认为这是可行的,尽管你需要对其进行一些严格的测试:

If you want to prevent the sum from exceeding 1000, apart from in cases where a single row has a value of greater than 1000, then I think this works, although you'll need to subject it to some rigorous testing:

SELECT NULL AS users_count, NULL AS total, NULL AS found
  FROM dual
 WHERE (@total := 0 OR @found := 0)
 UNION
SELECT users_count, @total AS total, @found := 1 AS found
  FROM messages_queue
 WHERE (@total := @total + users_count)
   AND @total < 1000
 UNION
SELECT users_count, users_count AS total, 0 AS found
  FROM messages_queue
 WHERE IF(@found = 0, @found := 1, 0);

这篇关于要选择的 SQL 查询,直到 SUM(users_count) 达到 1000的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)