mysql 如何让连续3周或以上的用户有序?

ymdaylpp  于 2022-11-21  发布在  Mysql
关注(0)|答案(3)|浏览(143)

我有一个用户表,

name      week_no   year_no
fb        5         2021
twitter   1         2022
twitter   2         2022
twitter   3         2022
twitter   7         2022
youtube  21         2022

我想找出在同一年连续3周登录的用户名。每一年的周数都是唯一的。例如,在上表中,我们可以看到用户twitter在同一年2022登录了week_no: 1, 2, 3,从而满足了我要寻找的条件。
我要找的输出,

name        year_no
twitter     2022

您可以使用以下方法创建示例表:

CREATE TABLE test (
    name varchar(20),
    week_no int,
    year_no int
);
INSERT INTO test (name, week_no, year_no)
VALUES ('fb', 5, 2021), 
       ('twitter', 1, 2022),
       ('twitter', 2, 2022),
       ('twitter', 3, 2022), 
       ('twitter', 7, 2022),
       ('youtube', 21, 2022);

我是SQL语言新手,我读过Group by可以实现这一点,有人能帮助我们使用什么函数/查询来实现这一点吗?

select * from test group by year_no, name;

提前感谢您的帮助。

u0sqgete

u0sqgete1#

一个简单的解决方案,将工作在每一个MySQL版本,而不使用windows功能。加入同一个表3次

SELECT t1.name,t1.year_no
FROM   test t1
INNER JOIN   test t2 ON t1.name=t2.name AND t1.year_no=t2.year_no
INNER JOIN   test t3 ON t1.name=t3.name AND t1.year_no=t3.year_no
WHERE  t2.week_no = t1.week_no + 1 
AND    t3.week_no = t1.week_no + 2

https://dbfiddle.uk/XjeXKUFE

klh5stk1

klh5stk12#

您可以为同一年中的连续周定义唯一的组,并按以下方式汇总它们:

SELECT name, year_no
FROM
(
  SELECT *, 
   week_no -
   ROW_NUMBER() OVER (PARTITION by name, year_no ORDER BY week_no) grp
 FROM test
) T
GROUP BY name, year_no, grp
HAVING COUNT(*) >= 3
ORDER BY name, year_no

请参见demo

xghobddn

xghobddn3#

窗口函数版本。
demo

WITH cte AS (
    SELECT
        name,
        week_no,
        year_no,
        lag(week_no) OVER (PARTITION BY name,
            year_no ORDER BY year_no,
            week_no) AS lag,
        lead(week_no) OVER (PARTITION BY name,
            year_no ORDER BY year_no,
            week_no) AS lead
    FROM
        testuser
)
SELECT DISTINCT
    name,
    year_no
FROM
    cte
WHERE
    lead + lag = 2 * week_no;

相关问题