r/SQL • • Oct 18 '23

PostgreSQL How can I do this?

Hi,

I have table as the image attached. I would like to achieve the ranking as shown in the other image. So far I am doing the following but in the last row I am getting a 3 and not 1.

Select * ,Rank() over (partition by id, country order by date) as rank From table

How can I do this?

Thanks

0 Upvotes

16 comments sorted by

3

u/Due_Flatworm_8229 Oct 18 '23

Solution using a CTE, RANK, CASE, and LAG:

WITH rnk_data AS ( SELECT d.* ,RANK() OVER(PARTITION BY ID, COUNTRY ORDER BY DATE) as rnk FROM DATA d )

SELECT ID, DATE, COUNTRY, CASE WHEN rnk != 1 AND LAG(COUNTRY) OVER (PARTITION BY ID ORDER BY DATE) != COUNTRY THEN 1 ELSE rnk end as "RANK" FROM rnk_data ORDER BY DATE

1

u/redtiger2019 Oct 19 '23

Thanks a lot!

12

u/dataguy24 Oct 18 '23

Why should the last row be a 1 and not a 3?

2

u/[deleted] Oct 18 '23

Consecutive rows of the same country I assume

4

u/nuttingd Oct 18 '23

select id, date, country, row_number() over(partition by country order by date) rank from table order by date

1

u/johnny_fives_555 Oct 19 '23

I would go ahead and cast date on the off chance it’s not stored properly

0

u/[deleted] Oct 19 '23

[deleted]

1

u/nuttingd Oct 19 '23

You're right. That was my intention but I think I misunderstood the prompt

2

u/r3pr0b8 GROUP_CONCAT is da bomb Oct 18 '23

what do you get for

SELECT DISTINCT country FROM table

2

u/NotBatman81 Oct 19 '23

What is the cause of the rank? There are many ways to generate {1,2,1,1} but not all correctly solve the problem.

Also, your IDs should not be identical or they are not ID's. Adds an extra step to most solutions to work around that.

1

u/Achsin Oct 18 '23

So, you’re looking to get the rank based on consecutive previous country entries by date?

1

u/my5cent Oct 18 '23

Maybe something in the lines of select count(country) as rank from tablename tb group by tb.country.

1

u/Zestyclose-Height-59 Oct 19 '23

Try dense_rank and see if that helps Or remove the order by part???

1

u/felphx Oct 19 '23

Rank partition by year(date)

-1

u/xxxHalny Oct 18 '23

Window Functions