尝试 select 数据,然后对 mariadb 中的 selected 数据进行平均
Trying to select data and then do a average on the selected data in mariadb
SELECT 计数
FROM (SELECT COUNT(ch_id
) AS 计数
来自 tbl_warrants_checked
WHERE status
= "活动"
分组 dateChecked
);
这使用 MariaDB 10.5,但应该适用于 ~10.2.2 之后的任何版本。
如果我们假设每天都有数据,或者我们不关心没有数据的日子,下面将计算自1个月前(最后一个月的数据)以来的平均每天检查:
-- Average of counts per day since ~1 month ago.
-- Only for days present in the set
SELECT AVG(counts) AS average
FROM (
SELECT COUNT(ch_id) AS counts
FROM tbl_warrants_checked
WHERE status = 'active'
AND dateChecked > (current_date - INTERVAL '1' MONTH)
GROUP BY dateChecked
) AS x
;
示例结果:
+---------+
| average |
+---------+
| 3.2941 |
+---------+
如果我们希望计算缺失的天数并将其视为 0,则以下生成自 1 个月前的天数和 LEFT JOIN
每天找到的天数:
-- Average of counts per day since ~1 month ago.
-- Treat missing days as 0
WITH RECURSIVE dates (date) AS (
SELECT current_date UNION ALL
SELECT date - INTERVAL '1' DAY FROM dates
WHERE date > (current_date - INTERVAL '1' MONTH)
)
SELECT AVG(COALESCE(counts, 0)) AS average
FROM dates AS d
LEFT JOIN (
SELECT dateChecked
, COUNT(ch_id) AS counts
FROM tbl_warrants_checked
WHERE status = 'active'
AND dateChecked > (current_date - INTERVAL '1' MONTH)
GROUP BY dateChecked
) AS x
ON d.date = x.dateChecked
;
示例结果:
+---------+
| average |
+---------+
| 1.7500 |
+---------+
Working test case with data which produces the above results
注意:我们也可以计算缺失的天数,并在没有递归和 JOIN
的情况下将其用于最终计算。还有另一种简化方法。
SELECT 计数
FROM (SELECT COUNT(ch_id
) AS 计数
来自 tbl_warrants_checked
WHERE status
= "活动"
分组 dateChecked
);
这使用 MariaDB 10.5,但应该适用于 ~10.2.2 之后的任何版本。
如果我们假设每天都有数据,或者我们不关心没有数据的日子,下面将计算自1个月前(最后一个月的数据)以来的平均每天检查:
-- Average of counts per day since ~1 month ago.
-- Only for days present in the set
SELECT AVG(counts) AS average
FROM (
SELECT COUNT(ch_id) AS counts
FROM tbl_warrants_checked
WHERE status = 'active'
AND dateChecked > (current_date - INTERVAL '1' MONTH)
GROUP BY dateChecked
) AS x
;
示例结果:
+---------+
| average |
+---------+
| 3.2941 |
+---------+
如果我们希望计算缺失的天数并将其视为 0,则以下生成自 1 个月前的天数和 LEFT JOIN
每天找到的天数:
-- Average of counts per day since ~1 month ago.
-- Treat missing days as 0
WITH RECURSIVE dates (date) AS (
SELECT current_date UNION ALL
SELECT date - INTERVAL '1' DAY FROM dates
WHERE date > (current_date - INTERVAL '1' MONTH)
)
SELECT AVG(COALESCE(counts, 0)) AS average
FROM dates AS d
LEFT JOIN (
SELECT dateChecked
, COUNT(ch_id) AS counts
FROM tbl_warrants_checked
WHERE status = 'active'
AND dateChecked > (current_date - INTERVAL '1' MONTH)
GROUP BY dateChecked
) AS x
ON d.date = x.dateChecked
;
示例结果:
+---------+
| average |
+---------+
| 1.7500 |
+---------+
Working test case with data which produces the above results
注意:我们也可以计算缺失的天数,并在没有递归和 JOIN
的情况下将其用于最终计算。还有另一种简化方法。