如何在MySql 5.5.34中获取一周中每天的前2个条目

hfyxw5xn  于 2022-12-17  发布在  Mysql
关注(0)|答案(1)|浏览(142)

我有一个MySQL表,其中包含列TENANT_NAMEMAX_CALLSTIME_STAMP,并且没有主键,根据我们插入数据的每小时的要求,相同的名称可以重复。
现在,我想获取像需要添加组名和总和调用,并获取前2项,每天在一周内。
例如:在22:49插入数据

TENANT_NAME,MAX_CALLS,TIME_STAMP
RS1, 20, 2022-12-07 22:49:17
RS2, 10, 2022-12-07 22:49:17
RS3, 2, 2022-12-07 22:49:17

在接下来的一小时23:49

RS1, 15, 2022-12-07 23:49:17
RS2, 0, 2022-12-07 23:49:17
RS3, 20, 2022-12-07 23:49:17

像这样,我有一年的数据
现在,我需要一周内name 2记录组的每天聚合
像这样

RS1, 35, MON
RS3, 22, MON... so on
RS4, 40, SUN
RS2, 35, SUN

我尝试了这个查询,我能够分组名称和总和呼叫,并显示DAYNAME,但我想在一周内每天的前2条记录。

select a.TENANT_NAME,SUM(a.MAX_CALLS),DAYNAME(a.TIME_STAMP) from TENANT_LIC_DISTRIBUTION AS a group by a.TENANT_NAME,day(a.TIME_STAMP) order by a.MAX_CALLS,a.TIME_STAMP;

RS1, 35, MON
RS3, 22, MON
RS2, 10, MON

RS3, 30, TUE
RS2, 20, TUE
RS1, 10, TUE.... so on
RS1, 20, SUN
RS2, 10, SUN
RS3, 1, SUN

我想像这样拿球

RS1, 35, MON
RS3, 22, MON

RS3, 30, TUE
RS2, 20, TUE.... so on

RS1, 20, SUN
RS2, 10, SUN

请帮帮我
谢谢

1tuwyuhd

1tuwyuhd1#

尝试在聚合查询周围使用window function来追加行号,然后通过行号进行限制。

WITH rank_tenant
AS (
    SELECT TENANT_NAME, 
    DAY, 
    CALLS, 
    row_number() OVER (
            PARTITION BY TENANT_NAME 
            ORDER BY CALLS DESC
            ) AS row_num
    FROM (select 
          TENANT_NAME,
          DAYNAME(TIME_STAMP) as DAY,
          SUM(MAX_CALLS) as CALLS
          from TENANT_LIC_DISTRIBUTION
          group by TENANT_NAME, DAY) as t1
    )
SELECT TENANT_NAME,
    DAY,
    CALLS
FROM rank_tenant
WHERE row_num <= 2;

相关问题