sql - PostgreSQL如何获取某些行的总和的平均值

标签 sql postgresql

如果标题不是很贴切,我深表歉意,但我在制定一个简洁的标题时遇到了一些麻烦。不管怎样,我有一个记录一个人所处状态的表格。它看起来像:

id, login, state, duration, started_at
1, pdiddy, working, 1200, 2018-05-25 08:30:00
2, pdiddy, lunch, 120, 2018-05-25 9:00:00
3, pdiddy, on_call, 65, 2018-05-25 12:30:00
4, pdiddy, available, 1115, 2018-05-25 12:30:00
5, pdiddy, working, 143, 2018-05-25 12:30:00
6, pdiddy, break1, 150, 2018-05-25 12:30:00
7, pdiddy, working, 2400, 2018-05-25 12:30:00
8, pdiddy, break2, 110, 2018-05-25 12:30:00

I need to get an average for only labor-related durations on a day-by-day basis for each user. So basically I need to add up the durations for everything other than "lunch", "break1", and "break2" for any given day and get the average for it.

I tried to do this like this, but the problem with this is that it doesn't add up the labor-related logs before averaging. I can't figure out how to do that.

SELECT
    log.login,
    AVG(log.duration) FILTER (WHERE log.state NOT IN ('lunch', 'break1', 'break2')) AS "labor_average"
FROM
    log
GROUP BY 1

显然,我不希望有人为我做这件事。我只需要指出正确的方向。我显然离解决方案还有很长的路要走,所以我只需要朝着正确的方向前进。非常感谢您!

最佳答案

我想你想要总和除以天数:

SELECT l.login,
       (SUM(l.duration) FILTER (WHERE l.state NOT IN ('lunch', 'break1', 'break2')) /
        COUNT(DISTINCT date_trunc('day', l.started_at)
       ) AS labor_average
FROM log l
GROUP BY l.login

关于sql - PostgreSQL如何获取某些行的总和的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50607651/

相关文章:

mysql - 获取 SQL 中 DISTINCT 值的总和并将其显示在记录中

java - TimescaleDB 的插入速度比普通 postgresql 10 慢

sql - 如何在单个 SQL Server 查询中选择多个组的一半?

mysql - 具有重复计数的条件 SQL Sum

delphi - 使用 Delphi 以编程方式向 pgAdmin 注册 Postgres 服务器

json - postgres-simple - 没有因使用 ‘query’ 而产生的 (ToRow Int) 实例

java - PSQLException 未被捕获

php - 在 Woocommerce 中根据客户总购买金额添加百分比折扣

SQL 挑战/谜题 : Given a stack trace - How to find the top element at each point in time?

sql - 选择锯齿模式中的最大值(局部最大值)