我不确定之前是否曾经问过,因为我不知道如何最好地表达这个问题。
给出如下查询:
SELECT DATE_FORMAT(i.created, '%Y-%m') as 'period',
COUNT(id) as 'total',
i.company_id
FROM invoice i
GROUP BY period, i.company_id
ORDER BY period DESC, total DESC
如何返回每月的平均和/或平均数,按company_id分组?重要的是只计算实际有发票的那些时期。
答案 0 :(得分:2)
如果您要排除零个月,请添加HAVING
条件,然后使用您的查询作为基础为每个公司选择AVG()
:
SELECT company_id, AVG(total)
FROM
(SELECT DATE_FORMAT(i.created, '%Y-%m') as 'period',
COUNT(id) as 'total',
i.company_id
FROM invoice i
GROUP BY period, i.company_id
HAVING COUNT(id)>0
) as T1
GROUP BY company_id