如何获取MySql中多个表的平均计数?

时间:2018-08-08 16:26:42

标签: mysql

_helper_calendar 表是一个简单的帮助程序表,用于填补日期空白,没有结果。这样我就可以获得开始日期和结束日期之间的每个日期。

我已经在每行代码中添加了解释,以便清楚地说明我要实现的目标。 我实际上得到的错误是:“无效使用组功能...”

这是我的查询:

   SELECT 
    /*get the day date*/
    cal.datefield AS cal_date, 
    /*get appointments by date from user*/
    (SELECT COUNT(e1.id) FROM events_table e1 WHERE DATE(e1.start) = DATE(cal.datefield) AND e1.user_id = 1 ) AS appointments, 
     /*get sales by date from user*/
    (SELECT COUNT(s1.id) FROM sales_table s1 WHERE DATE(s1.created) = DATE(cal.datefield) AND s1.user_id  = 1) AS sales,
       /*get average appointments by date from all users*/
    (SELECT COUNT(e2.id) FROM events_table e2 WHERE DATE(e2.start) = DATE(cal.datefield) ) AS appointments_avg, 
      /*get average sales by date from all users*/
    (SELECT AVG(COUNT(s2.id)) FROM sales_table s2 WHERE DATE(s2.created) = DATE(cal.datefield)) AS sales_avg
FROM events_table e 
    RIGHT JOIN _helper_calendar AS cal ON (DATE(e.start) = cal.datefield)
WHERE DATE(cal.datefield) BETWEEN '2018-06-01' AND '2018-07-31' 
GROUP BY cal_date

这是一个较短的查询,它产生相同的错误。当然,我需要它在与上述相同的环境中工作,但这也许有助于更好地理解?

SELECT s.start, AVG(COUNT(s.id)) s2_cnt FROM sales_table s WHERE DATE(s.start) BETWEEN '2018-06-01' AND '2018-07-31'  GROUP BY DATE(s.start);

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

使用从日历表到其他表的左联接并使用按日期分组的聚合函数来重写查询:

SELECT
    cal.datefield AS cal_date,
    COUNT(e1.id) AS appointments, 
    COUNT(s1.id) AS sales
FROM _helper_calendar AS cal
LEFT JOIN events_table e ON DATE(e.start) = cal.datefield
LEFT JOIN events_table e1 ON DATE(e1.start) = DATE(cal.datefield)
   AND e1.user_id = 1
LEFT JOIN salestable ON DATE(s1.created) = DATE(cal.datefield)
   AND s1.user_id = 1
WHERE DATE(cal.datefield) BETWEEN '2018-06-01' AND '2018-07-31'
GROUP BY cal.datefield

,然后将此查询与另一个查询结合,该查询将获得每个用户在该日期加入的每个日期的平均值。