gpt4 book ai didi

mysql - 按第一次和最后一次出现分组

转载 作者:可可西里 更新时间:2023-11-01 08:39:46 27 4
gpt4 key购买 nike

我有一个如下表:

    +-------------+--------------+
| current_day | browser |
+-------------+--------------+
| 2016-05-02 | Safari |
| 2016-05-03 | Safari |
| 2016-05-04 | Safari |
| 2016-05-05 | Safari |
| 2016-05-06 | Safari |
| 2016-05-07 | Safari |
| 2016-05-08 | Safari |
| 2016-05-09 | Opera |
| 2016-05-10 | Opera |
| 2016-05-11 | Opera |
| 2016-05-12 | Opera |
| 2016-05-13 | Opera |
| 2016-05-14 | Opera |
| 2016-05-15 | Chrome |
| 2016-05-16 | Firefox |
| 2016-05-17 | Firefox |
| 2016-05-18 | Firefox |
| 2016-05-19 | Firefox |
| 2016-05-20 | Firefox |
| 2016-05-21 | Firefox |
| 2016-05-22 | Firefox |
| 2016-05-23 | Safari |
| 2016-05-24 | Safari |
| 2016-05-25 | Safari |
| 2016-05-26 | Safari |
| 2016-05-27 | Safari |
| 2016-05-28 | Safari |
| 2016-05-29 | Safari |
| 2016-05-30 | Opera |
| 2016-05-31 | Opera |
| 2016-06-01 | Opera |
| 2016-06-02 | Firefox |
| 2016-06-03 | Firefox |
| 2016-06-04 | Firefox |
| 2016-06-05 | Firefox |
| 2016-06-06 | Firefox |
| 2016-06-07 | Firefox |
| 2016-06-08 | Firefox |
| 2016-06-09 | Chrome |
| 2016-06-10 | Chrome |
| 2016-06-11 | Chrome |
| 2016-06-12 | Chrome |
| 2016-06-13 | Chrome |
| 2016-06-14 | Chrome |
| 2016-06-15 | Chrome |
| 2016-06-16 | Chrome |
+-------------+--------------+

我想提取“浏览器”列中每个序列的第一次和最后一次出现,换句话说,结果如下:

    +-------------+--------------+
| current_day | browser |
+-------------+--------------+
| 2016-05-02 | Safari |
| 2016-05-08 | Safari |
| 2016-05-09 | Opera |
| 2016-05-14 | Opera |
| 2016-05-15 | Chrome |
| 2016-05-16 | Firefox |
| 2016-05-22 | Firefox |
| 2016-05-23 | Safari |
| 2016-05-29 | Safari |
| 2016-05-30 | Opera |
| 2016-06-01 | Opera |
| 2016-06-02 | Firefox |
| 2016-06-08 | Firefox |
| 2016-06-09 | Chrome |
| 2016-06-16 | Chrome |
+-------------+--------------+

是否可以/方便地创建 MYSQL 查询?还是提取所有结果并使用 php 执行一些后处理更好?

最佳答案

您可以使用以下查询:

SELECT MIN(current_day) AS start_day, 
MAX(current_day) AS stop_day,
browser
FROM (
SELECT current_day, browser,
@grp := IF(@br = browser, @grp,
IF(@br := browser, @grp+1, @grp+1)) AS grp
FROM mytable
CROSS JOIN (SELECT @grp := 0, @br := '') AS vars
ORDER BY current_day) AS t
GROUP BY browser, grp

上述查询使用变量,以识别具有相同 browser 值的连续记录的孤岛。它为每个浏览器返回一行。如果您想为每个最小/最大日期获取两个 单独的行,则必须重复相同的子查询两次并使用UNION

Demo here

关于mysql - 按第一次和最后一次出现分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37882795/

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