简体   繁体   中英

how to get top 2 entries from each day in a week in MySql 5.5.34

I have a MySQL table with columns TENANT_NAME , MAX_CALLS , and TIME_STAMP and there is no primary key , as per requirement for every hour we are inserting data and the same names can be repeated.

now I want to fetch like need to add group names and sum calls and fetch the top 2 entries per day in a week.

Ex: data insert at 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

in the next hour at 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

like this, I have 1 year of data

now i want per day aggregation of groups of name 2 records of a week

like this

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

I tried this query and I am able to group names and sum total calls, and display DAYNAME but I want the top 2 records per day of in a week.

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

and I want to fetch like this

RS1, 35, MON
RS3, 22, MON

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

RS1, 20, SUN
RS2, 10, SUN

please help me

Thanks

Try using a window function around your aggregation query to append row numbers, and then limit by row number. Here's one way.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM