【问题标题】:How can I get the average number of distinct users per day of the week?如何获得一周中每天不同用户的平均数量?
【发布时间】:2019-08-09 21:19:09
【问题描述】:

我正在尝试使用 SQLite 获取一周中每天不同客户和员工的平均数量(即,平均周二有多少不同客户致电?)。

这是一些示例数据。这些日期都是星期二,因此在这种情况下,星期二的不同客户的平均数量是 1,而工作的不同员工的平均数量是 3:

 id   starttime           customer  employee
 1    2019-01-01 12:00    1         1
 2    2019-01-01 12:00    1         2
 3    2019-01-01 12:00    1         3
 4    2019-01-08 12:00    2         1
 5    2019-01-08 12:00    2         2
 6    2019-01-08 12:00    2         3
 7    2019-01-15 12:00    3         1
 8    2019-01-15 12:00    3         2
 9    2019-01-15 12:00    3         3



select strftime('%w', starttime) as day_number,
count(distinct customer) / count(distinct starttime) as 
    avg_customer,
count(distinct employee) / count(distinct starttime) as 
    avg_employee
from logins
group by strftime('%w', starttime);

我尝试了上面的代码,它适用于客户(输出为 1)但不适用于员工(输出为 1,但应该为 3),我现在意识到这是因为我需要计算每个日期的计数,然后除以按日期数,而不是计算所有日期的不同员工,然后除以日期数,但我正在努力解决这个问题。

【问题讨论】:

    标签: sql sqlite


    【解决方案1】:

    如何获得一周中每天不同用户的平均数量?

    1. 获取每天不同用户的数量。
    2. 获取每周平均值。

    查询:

    select
      strftime('%w', day) as week,
      avg(customers) as avg_customer,
      avg(employees) as avg_employee
    from
    (
      select
        date(starttime) as day,
        count(distinct customer) as customers,
        count(distinct employee) as employees
      from logins
      group by date(starttime)
    ) days
    group by strftime('%w', day)
    order by strftime('%w', day);
    

    【讨论】:

      【解决方案2】:

      你需要删除这两个

      / count(distinct starttime)
      

      因此,您会得到一个查询,该查询会为您提供每天不同客户和员工的数量。

      然后,将整个查询嵌套在另一个简单地平均这些字段的查询中

      Select AVG(distinct_customers), AVG(distinct_employees) from (your query)
      

      这是一个很好的经验法则,在对任何事情进行平均时,直到最后一步才进行除法,先将所有内容相加,然后再除。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-11
        • 2015-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-08
        • 2015-08-14
        相关资源
        最近更新 更多