Home > Software design >  sql - How To Remove All Rows After 4th Occurence of Column Combination in postgresql
sql - How To Remove All Rows After 4th Occurence of Column Combination in postgresql

Time:10-28

I have a sql query that results in a table similar to the following after grouping by name, quarter, year and ordering by year DESC, quarter DESC:

name count quarter year
orange 22 4 2022
apple 1 4 2022
banana 123 3 2022
pie 93 2 2022
apple 12 2 2022
orange 0 1 2022
apple 900 4 2021
... ... ... ...

I want to remove any rows that come after the 4th unique combination of quarter and year is reached (for the table above this would be any rows after the last combination of quarter 1, year 2022), like so:

name count quarter year
orange 22 4 2022
apple 1 4 2022
banana 123 3 2022
pie 93 2 2022
apple 12 2 2022
orange 0 1 2022

I am using Postgres 6.10.

If the next year were reached, it would still need to work with the quarter at the top being 1 and the year 2023.

CodePudding user response:

select  name 
       ,count 
       ,quarter 
       ,year
from
(
select  *
       ,dense_rank() over(order by year desc, quarter desc) as dns_rnk
from    t
) t
where   dns_rnk <= 4
name count quarter year
orange 22 4 2022
apple 1 4 2022
banana 123 3 2022
pie 93 2 2022
apple 12 2 2022
orange 0 1 2022

Fiddle

  • Related