sqlpostgresqlgroup-bywindow-functionsdistinct-on

How to get the max amount per day for a month


I have a table with two columns: demo at db<>fiddle

create table your_table("Date","Count")as values
 ('2022-01-13'::date,   8)
,('2022-01-18'::date,   14)
,('2022-01-25'::date,   24)
,('2022-02-08'::date,   50)
,('2022-02-15'::date,   15)
,('2022-03-01'::date,   6)
,('2022-03-09'::date,   32)
,('2022-03-15'::date,   10);

and I want to get the following result. Max amount per day for a month

Date Count
2022-01-25 24
2022-02-08 50
2022-03-09 32

I can’t group the query so that the result is months and days with the maximum count


Solution

  • Try using ROW_NUMBER() and CTE.

    Table:

    create table test_dt 
    (
        dts date,
        amt int
    );
    

    Sample data:

    insert into test_dt values('2025-03-14',10),('2025-03-11',20),('2025-03-13',19),('2025-03-16',80); 
    insert into test_dt values('2025-02-01',10),('2025-02-03',40),('2025-02-08',15),('2025-02-04',99); 
    insert into test_dt values('2025-01-17',10),('2025-01-13',60),('2025-01-11',87),('2025-01-21',16);  
    

    Query:

    with cte as 
    ( 
     select *,row_number() over(partition by to_char(dts,'YYYY-MM') order by amt desc) rnk  
     from test_dt 
    ) 
    select dts,amt  
    from cte c 
    where rnk = 1;
    

    Output:

    dts amt
    2025-01-11 87
    2025-02-04 99
    2025-03-16 80