gpt4 book ai didi

php - 从表的末尾获取连续值的数量

转载 作者:行者123 更新时间:2023-11-29 06:43:17 25 4
gpt4 key购买 nike

我需要这方面的帮助,我不知道该怎么做。

这是我在 MySql 中的数据

----------------------
| id | color |
----------------------
| 1 | green |
| 2 | red |
| 3 | red |
| 4 | black |
| 5 | red |
| 6 | black |
| 7 | black |
----------------------

如何统计最后一个颜色的数据?但不是在所有行中,我只想计算最后一个数据的时间是多少。在这种情况下结果应该是:

黑色连续2次

----------------------
| id | color |
----------------------
| 1 | green |
| 2 | red |
| 3 | red |
| 4 | black |
| 5 | red |
| 6 | black |
| 7 | black |
| 9 | green |
| 10 | red |
| 11 | red |
| 12 | red |
----------------------

这里将是:

红色连续3次

最佳答案

这似乎是用户定义变量的有效案例。无论 ID 列是否具有连续值,此解决方案都有效:

select max(amount) amount from (
select color,
@found := if(@found, true, @prev_color != color),
@prev_color := color,
@amount := @amount + (not @found) amount
from table, (
select @prev_color := (select color from table order by id desc limit 1),
@found := false,
@amount := 0) init
order by id desc
) s

看到它工作 here .

关于php - 从表的末尾获取连续值的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20112128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com