Skip to content
Advertisement

Trying to select data and then do a average on the selected data in mariadb

SELECT counts FROM (SELECT COUNT(ch_id) AS counts FROM tbl_warrants_checked WHERE status = “active” GROUP BY dateChecked);

enter image description here

enter image description here

Advertisement

Answer

This uses MariaDB 10.5, but should work with any version since ~10.2.2.

If we assume every day has data, or we don’t care about the days which have no data, the following will calculate the average checks per day since 1 month ago (the last month of data):

Sample result:

If we wish to account for missing days and treat them as 0, the following generates the days since 1 month ago and LEFT JOINs that with the found counts per day:

Sample result:

Working test case with data which produces the above results

Note: We could also have calculated the missing days and used that in the final calculation without the recursion and JOIN. There’s another simplification available as well.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement