Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql Sql获取Sql中最新的n行,其总和大于或等于某个值_Mysql_Sql - Fatal编程技术网

Mysql Sql获取Sql中最新的n行,其总和大于或等于某个值

Mysql Sql获取Sql中最新的n行,其总和大于或等于某个值,mysql,sql,Mysql,Sql,我有以下数据的fb_数据表 id sessions created_at 1 25 2020-05-28 12:00:00 2 30 2020-05-28 13:00:00 3 24 2020-05-29 14:00:00 我想得到其总和大于40的最新行。例如,id 2和3创建的总和大于40。如果您使用的是MySQL 8+,那么我只需要2行和3行,不包括第1行,那么老实说,最简单的方法就是使用分析函数: WITH cte AS ( SELECT

我有以下数据的fb_数据表

id sessions created_at

1   25     2020-05-28 12:00:00

2   30     2020-05-28 13:00:00

3   24     2020-05-29 14:00:00

我想得到其总和大于40的最新行。例如,id 2和3创建的总和大于40。如果您使用的是MySQL 8+,那么我只需要2行和3行,不包括第1行,那么老实说,最简单的方法就是使用分析函数:

WITH cte AS (
    SELECT *, SUM(sessions) OVER (ORDER BY created_at DESC) sum_sessions
    FROM yourTable
)

SELECT t1.id, t1.sessions, t1.created_at
FROM yourTable t1
WHERE t1.created_at >= (SELECT MAX(t2.created_at) FROM cte t2
                        WHERE t2.sum_sessions > 40);
以下是CTE中定义的中间结果:

id | sessions | created_at          | sum_sessions
1  | 25       | 2020-05-28 12:00:00 | 79
2  | 30       | 2020-05-28 13:00:00 | 54   <-- most recent date having required sum
3  | 24       | 2020-05-29 14:00:00 | 24
id | sessions |在| sum | sessions创建
1  | 25       | 2020-05-28 12:00:00 | 79

2 | 30 | 2020-05-28 13:00:00 | 54您可以使用
sum()
window函数获取每行的会话总数。
因此,您需要所有行的总和减去其
sessions
值小于(或等于?)40:


您可以这样做:

select * from (select *,sum(session_name) OVER (ORDER BY Id)x from t1 ) a where x>40

使用第1行和第2行来满足要求会有什么问题?因为我需要创建SUM的最新数据。您使用的MySQL版本是什么?MySQL版本8.0
| id  | sessions | created_at          |
| --- | -------- | ------------------- |
| 3   | 24       | 2020-05-29 14:00:00 |
| 2   | 30       | 2020-05-28 13:00:00 |
select * from (select *,sum(session_name) OVER (ORDER BY Id)x from t1 ) a where x>40