I was asked this question in a job interview:
There is a table with vehicle names mentioned in a column. Output when we check for name=car we must get as 4 i.e the maximum count of continuous occurrence of ‘car’ in the column.
Can somebody help me get this solution in PostgreSQL?
I tried using rank and dense rank but it didn’t work.
2
Answers
Disclaimer: As already stated by @Mureinik in the comments: This can only work if there is a dedicated column for ordering (e.g. an increasing ID or a timestamp). The reason is, that in the database the column order is not determined. So you always need a sort order criterion if you’d deal with specific orders. In the example below I added an
id
column.step-by-step demo: db<>fiddle
name
group.COUNT()
window function to count the records of each group.This is a gaps and islands problem, you could try the difference between two row numbers to solve it.
This can be done only if there is a column you can order by (e.g. an increasing ID or a timestamp) as mentioned by @Mureinik and @S-Man :
To get the maximum count of continuous occurrence for all names, just remove the
where
clauseDemo here