Skip to content
Advertisement

SQL SELF JOIN – driving me crazy

Can someone please tell me how to solve this question? And the thought process – like how do you think while solving this. It is driving me crazy. 🙁

Question – The attendance table logs the number of people counted in a crowd each day an event is held. Write a query to return a table showing the date and visitor count of high-attendance periods, defined as three consecutive entries (not necessarily consecutive dates) with more than 100 visitors.

Question code on oracle –

QUESTION TABLE AND DESIRED OUTPUT

enter image description here

Advertisement

Answer

There are several ways to approach this, but a self-join does not come to mind.

The most general would use a gaps-and-islands approach. However, I’m going to suggest a more brute-force method. Simply use lead() and lag() to get the values from the previous and next rows. Then use a where clause to see if there are three in a row that meet your condition:

Here is a db<>fiddle.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement