Support all time resolutions on all counter views
This commit is contained in:
79
app/queries/monthly_stats.py
Normal file
79
app/queries/monthly_stats.py
Normal file
@@ -0,0 +1,79 @@
|
||||
import logging
|
||||
from queries.connection import connection
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def get_all_monthly_analytics(end_date:str = 'now'):
|
||||
try:
|
||||
return connection.query('''
|
||||
WITH RECURSIVE timeseries(d) AS (
|
||||
VALUES(date(:end_date,'start of year'))
|
||||
UNION ALL
|
||||
SELECT date(d, '+1 month') as d
|
||||
FROM timeseries
|
||||
WHERE d < date(:end_date, '-1 month')
|
||||
),
|
||||
months AS (
|
||||
SELECT
|
||||
strftime('%m',d) as m,
|
||||
strftime('%Y',d) as y
|
||||
FROM timeseries
|
||||
),
|
||||
stats AS (
|
||||
SELECT
|
||||
strftime('%m', timestamp) as m,
|
||||
strftime('%Y', timestamp) as y,
|
||||
counter_id,
|
||||
sum(increment) as count
|
||||
FROM entries
|
||||
group by counter_id, strftime('%m', timestamp), strftime('%Y', timestamp)
|
||||
)
|
||||
select
|
||||
concat(m.m,', ',m.y) as "month",
|
||||
case
|
||||
when counter_id is null then json_object()
|
||||
else json_group_object(name, count)
|
||||
end as counters
|
||||
FROM months m
|
||||
left outer join stats t on m.m = t.m and m.y = t.y
|
||||
left join counters c on t.counter_id = c.id
|
||||
GROUP by m.m, m.y
|
||||
''', params={"end_date": end_date}, ttl=0)
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
return None
|
||||
|
||||
def get_monthly_analytics(counter_id:int, end_date:str = 'now'):
|
||||
try:
|
||||
return connection.query('''
|
||||
WITH RECURSIVE timeseries(d) AS (
|
||||
VALUES( date(:end_date, 'start of year'))
|
||||
UNION ALL
|
||||
SELECT date(d, '+1 month')
|
||||
FROM timeseries
|
||||
WHERE d < date(:end_date, '-1 month')
|
||||
),
|
||||
months AS (
|
||||
SELECT
|
||||
strftime('%m',d) as m,
|
||||
strftime('%Y',d) as y
|
||||
FROM timeseries
|
||||
),
|
||||
stats AS (
|
||||
SELECT
|
||||
strftime('%m', timestamp) as m,
|
||||
strftime('%Y', timestamp) as y,
|
||||
sum(increment) as count
|
||||
FROM entries
|
||||
where counter_id = :id
|
||||
group by strftime('%m', timestamp), strftime('%Y', timestamp)
|
||||
)
|
||||
SELECT
|
||||
concat(m.m,', ',m.y) as "month",
|
||||
coalesce(s.count, 0) as count
|
||||
FROM months as m
|
||||
LEFT JOIN stats as s on s.m = m.m and s.y = m.y
|
||||
''', params={'id': counter_id, "end_date": end_date}, ttl=0)
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
return None
|
||||
Reference in New Issue
Block a user