https://www.sqlteam.com/articles/detecting-runs-or-streaks-in-your-data
GameDate Result 1/1/2000 W 1/12/2000 L 1/15/2000 W 1/17/2000 W 1/22/2000 W 2/1/2000 L 2/5/2000 W 2/8/2000 L 2/16/2000 W 2/19/2000 L 2/25/2000 L 2/28/2000 L 3/15/2000 L 3/19/2000 W 3/25/2000 W
- Do a self join with table - do a cross join with all the previous dates where result is not matching - count number of rows above a record where record is not matching - This becomes the run group
SELECT GameDate, Result, (SELECT COUNT(*) FROM GameResults G WHERE G.Result <> GR.Result AND G.GameDate <= GR.GameDate) as RunGroup FROM GameResults GR
GameDate Result RunGroup 1/1/2000 W 0 1/12/2000 L 1 1/15/2000 W 1 1/17/2000 W 1 1/22/2000 W 1 2/1/2000 L 4 2/5/2000 W 2 2/8/2000 L 5 2/16/2000 W 3 2/19/2000 L 6 2/25/2000 L 6 2/28/2000 L 6 3/15/2000 L 6 3/19/2000 W 7 3/25/2000 W 7
-- Now we need to group by Result and Run Group and find how many games are played
SELECT Result, MIN(GameDate) as StartDate, MAX(GameDate) as EndDate, COUNT(*) as Games FROM (SQL 1) A GROUP BY Result, RunGroup ORDER BY Min(GameDate)
Result StartDate EndDate Games W 1/1/2000 1/1/2000 1 L 1/12/2000 1/12/2000 1 W 1/15/2000 1/22/2000 3 L 2/1/2000 2/1/2000 1 W 2/5/2000 2/5/2000 1 L 2/8/2000 2/8/2000 1 W 2/16/2000 2/16/2000 1 L 2/19/2000 3/15/2000 4 W 3/19/2000 3/25/2000 2
No comments:
Post a Comment