Created
November 10, 2015 10:20
-
-
Save brainwire/07ec4589e930604bb785 to your computer and use it in GitHub Desktop.
Как найти самый длинный непрерывный ряд событий с помощью SQL http://habrahabr.ru/post/270573/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| WITH | |
| -- This table contains all the distinct date | |
| -- instances in the data set | |
| dates(date) AS ( | |
| SELECT DISTINCT CAST(CreationDate AS DATE) | |
| FROM Posts | |
| WHERE OwnerUserId = ##UserId## | |
| ), | |
| -- Generate "groups" of dates by subtracting the | |
| -- date's row number (no gaps) from the date itself | |
| -- (with potential gaps). Whenever there is a gap, | |
| -- there will be a new group | |
| groups AS ( | |
| SELECT | |
| ROW_NUMBER() OVER (ORDER BY date) AS rn, | |
| dateadd(day, -ROW_NUMBER() OVER (ORDER BY date), date) AS grp, | |
| date | |
| FROM dates | |
| ) | |
| SELECT | |
| COUNT(*) AS consecutiveDates, | |
| MIN(week) AS minDate, | |
| MAX(week) AS maxDate | |
| FROM groups | |
| GROUP BY grp | |
| ORDER BY 1 DESC, 2 DESC |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| WITH | |
| weeks(week) AS ( | |
| SELECT DISTINCT datepart(year, CreationDate) * 100 | |
| + datepart(week, CreationDate) | |
| FROM Posts | |
| WHERE OwnerUserId = ##UserId## | |
| ), | |
| groups AS ( | |
| SELECT | |
| ROW_NUMBER() OVER (ORDER BY week) AS rn, | |
| dateadd(day, -ROW_NUMBER() OVER (ORDER BY week), week) AS grp, | |
| week | |
| FROM weeks | |
| ) | |
| SELECT | |
| COUNT(*) AS consecutiveWeeks, | |
| MIN(week) AS minWeek, | |
| MAX(week) AS maxWeek | |
| FROM groups | |
| GROUP BY grp | |
| ORDER BY 1 DESC, 2 DESC |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment