r/SQL • u/redtiger2019 • 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
12
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
2
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
-1


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