@@ -297,33 +297,38 @@ def report_monthly(db_path: str, month_str: str) -> None:
297297 else :
298298 next_month = f"{ year } -{ month + 1 :02d} -01"
299299
300- # Get all game sessions in the month, ordered by date
300+ # Get monthly playtime by calculating the difference between the last session
301+ # in the month and the last session before the month started
301302 cur .execute ('''
302- WITH monthly_data AS (
303- SELECT
304- g.name,
305- s.appid,
306- s.date,
307- s.playtime_minutes,
308- LAG(s.playtime_minutes) OVER (
309- PARTITION BY s.appid
310- ORDER BY s.date
311- ) AS prev_playtime
303+ WITH month_sessions AS (
304+ -- Get all sessions within the target month
305+ SELECT s.appid, g.name, s.date, s.playtime_minutes
312306 FROM sessions s
313307 JOIN games g ON s.appid = g.appid
314308 WHERE s.date >= ? AND s.date < ?
315- ORDER BY s.date
309+ ),
310+ pre_month_baseline AS (
311+ -- Get the last session before the month for each game
312+ SELECT s.appid, MAX(s.playtime_minutes) as baseline_playtime
313+ FROM sessions s
314+ WHERE s.date < ?
315+ GROUP BY s.appid
316+ ),
317+ month_end_playtime AS (
318+ -- Get the last session in the month for each game
319+ SELECT ms.appid, ms.name, MAX(ms.playtime_minutes) as end_playtime
320+ FROM month_sessions ms
321+ GROUP BY ms.appid
316322 )
317323 SELECT
318- name,
319- appid,
320- SUM(CASE WHEN prev_playtime IS NULL THEN playtime_minutes
321- ELSE MAX(0, playtime_minutes - prev_playtime) END) AS total_minutes
322- FROM monthly_data
323- GROUP BY appid
324- HAVING total_minutes > 0
325- ORDER BY total_minutes DESC
326- ''' , (month_start , next_month ))
324+ mep.name,
325+ mep.appid,
326+ mep.end_playtime - COALESCE(pmb.baseline_playtime, 0) as monthly_playtime
327+ FROM month_end_playtime mep
328+ LEFT JOIN pre_month_baseline pmb ON mep.appid = pmb.appid
329+ WHERE mep.end_playtime - COALESCE(pmb.baseline_playtime, 0) > 0
330+ ORDER BY monthly_playtime DESC
331+ ''' , (month_start , next_month , month_start ))
327332
328333 rows = cur .fetchall ()
329334
@@ -333,7 +338,7 @@ def report_monthly(db_path: str, month_str: str) -> None:
333338
334339 print (f"Monthly report for { month_str } :" )
335340 for row in rows :
336- print (f"- { row ['name' ]} : { format_playtime (row ['total_minutes ' ])} " )
341+ print (f"- { row ['name' ]} : { format_playtime (row ['monthly_playtime ' ])} " )
337342
338343 conn .close ()
339344 except sqlite3 .Error as e :
0 commit comments