从表中连接记录的日期明智平均值

时间:2016-03-07 07:02:04

标签: mysql

结构

Table: HOUSEHOLD (id, form_date)

TABLE: HOUSEHOLD_MEMBERS (id, HOUSEHOLD_ID, MEMBER_NAME, ... )

e.g。对于给定的家庭,HOUSEHOLD_MEMBERS表中可能有5,6,8,10个家庭成员。

我正在尝试

指定日期的平均家庭成员数。

输出应该是:

[DATE, AVERAGE]

[2016-03-01, 5.4]
[2016-03-02, 4.9]
[2016-03-03, 6.7]

到目前为止我做了什么

SELECT 
DATE(HOUSEHOLD.form_date) AS DATE_ONLY,

    (SELECT COUNT(*) FROM HOUSEHOLD_MEMBERS WHERE HOUSEHOLD.id = HOUSEHOLD_MEMBERS.HOUSEHOLD_ID) AS COUNT

FROM
DATA
GROUP BY DATE_ONLY

它远非我所期待的结果,我们将非常感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

我认为这可能就是你要找的东西:

SELECT HDATE, AVG(cnt)
FROM (
  SELECT DATE(H.FORM_DATE) AS HDATE, COUNT(*) AS cnt
  FROM HOUSEHOLD_MEMBER AS HM
  INNER JOIN HOUSEHOLD AS H ON HM.HOUSEHOLD_ID = H.ID
  GROUP BY DATE(H.FORM_DATE), H.ID) AS t
GROUP BY HDATE

内部查询返回每个家庭每个日期的成员数。外部查询返回每个日期的平均数。

答案 1 :(得分:2)

试试这个:

SELECT 
    DATE(h.form_date) AS DATE,
    COUNT(*)/COUNT(DISTINCT h.id) AS AVERAGE
FROM
    HOUSEHOLD h INNER JOIN HOUSEHOLD_MEMBERS hm ON h.id = hm.HOUSEHOLD_ID
GROUP BY DATE;

答案 2 :(得分:0)

试试这个sql

select from_date,AVG(HOUSEHOLD_ID) from HOUSEHOLD as h join HOUSEHOLD_MEMBERS as hm
on hm.HOUSEHOLD_ID=h.id GROUP BY from_date