Skip to content
Advertisement

Sqlite, using grouping? for subqueries with date ranges

I have a sqlite query that works as-is and it’s used to get an average of date between a date range

SELECT AVG(activity) as activity from activityDate WHERE DATE(activityDate) between '2019-11-01' and '2019-11-31

Again, this works perfectly but I’d like to do some kind of subquery operation that does this same thing for every month and returns the result for each as a different alias like this

SELECT 
        (AVG(activity) from activityDate WHERE DATE(activityDate) between '2019-11-01' and '2019-11-31') as novemberActivity
        (AVG(activity) from activityDate WHERE DATE(activityDate) between '2019-12-01' and '2019-12-31') as decemberActivity

        //?

but my issue is after doing those alias rows, what do i do as the FROM statement?

I just want to be able to return 12 results, an average for each month with its own alias.

Advertisement

Answer

I think you want conditional aggregation:

SELECT AVG(CASE WHEN DATE(activityDate) between '2019-11-01' and '2019-11-30' THEN activity END) as activity_201911,
       AVG(CASE WHEN DATE(activityDate) between '2019-12-01' and '2019-12-31' THEN activity END) as activity_201912       
FROM activityDate 
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement