MYSQL COUNT结果和AVG它们在按列分组时

时间:2017-10-27 17:28:22

标签: mysql

我正在尝试选择过去30天内每天的平均完成次数,然后对其进行平均。这是我的Rundown表的一个例子

RundownID | WorkOrderID | ForemanID | Completion | RundownDate
1         | 1           | 1         | 1          | 2017-10-27
2         | 2           | 1         | 1          | 2017-10-26
3         | 3           | 1         | 1          | 2017-10-20
4         | 4           | 1         | 1          | 2017-10-27
5         | 5           | 2         | 1          | 2017-10-27
6         | 6           | 2         | 1          | 2017-10-27
7         | 7           | 3         | 1          | 2017-10-25
8         | 8           | 2         | 0          | 2017-10-20

我正在寻找的结果是

ForemanID | ForemanAvg
1         | 4
2         | 2
3         | 1

应该采用过去30天内的完成行总数,并计算每个唯一ForemanID的每日总数。然后平均每天的总数给出我过去30天的平均值

我知道我很亲密,但我似乎无法正确配置它。这是我有多远

SELECT
    ForemanID,
    COUNT(RundownDate) AS ForemanAvg
FROM Rundown
WHERE RundownDate > (DATE_SUB(CURDATE(), INTERVAL '30' Day))
AND Completion = 1
GROUP BY ForemanID 

结果

ForemanID | ForemanAvg
23        | 70
24        | 100
25        | 100
26        | 76
27        | 109
29        | 11

编辑:

我越走越近了。使用以下查询我得到了我想要的结果,但是由于某种原因它只给了我一个ForemanID

SELECT 
    a.ForemanID,
    AVG(a.ForemanAvg)
FROM (SELECT
    RundownDate,
    ForemanID,
    COUNT(RundownDate) AS ForemanAvg
FROM Rundown
WHERE RundownDate > (DATE_SUB(CURDATE(), INTERVAL '30' Day))
AND Completion = 1
GROUP BY ForemanID, RundownDate ) AS a

2 个答案:

答案 0 :(得分:2)

以下查询应该有效:

SELECT
    ForemanID,
    count(*)/COUNT(distinct RundownDate) AS ForemanAvg
FROM Rundown
WHERE RundownDate > (DATE_SUB(CURDATE(), INTERVAL '30' Day))
AND Completion = 1
GROUP BY ForemanID;

希望它有所帮助!

答案 1 :(得分:1)

如果您想“平均每个唯一ForemanID的每日总数”,那么您需要将日期添加到分组中:

SELECT
    ForemanID,
    COUNT(Completion) AS ForemanAvg
FROM Rundown
WHERE RundownDate > (DATE_SUB(CURDATE(), INTERVAL '30' Day))
AND Completion = 1
GROUP BY ForemanID, RundownDate 

注意:这不是“平均”,这是一个计数。如果您真的想要平均值,请使用AVG(Completion)代替COUNT(Completion)

编辑要添加除日常总数之外的平均行,您可以在其他查​​询中执行此操作,并使用UNION组合这两个查询。

SELECT
    ForemanID,
    COUNT(Completion) AS ForemanAvg
FROM Rundown
WHERE RundownDate > (DATE_SUB(CURDATE(), INTERVAL '30' Day))
AND Completion = 1
GROUP BY ForemanID, RundownDate 
UNION
SELECT
    ForemanID,
    AVG(Completion) AS ForemanAvg
FROM Rundown
WHERE RundownDate > (DATE_SUB(CURDATE(), INTERVAL '30' Day))
AND Completion = 1
GROUP BY ForemanID
ORDER BY ForemanID