【问题标题】:How to get the average of the number of actions per day如何获得平均每天的操作次数
【发布时间】:2021-11-11 09:02:22
【问题描述】:

我已经写了sql查询:

SELECT id
       date_diff("day", create_date, date) as day
       action_type
FROM "my_database"

它带来了这个:

id     day      action_type
1       0        upload     
1       0        upload 
1       0        upload 
1       1        upload 
1       1        upload 
2       0        upload 
2       0        upload 
2       1        upload 

如何更改我的查询以获取列中具有唯一天数的表,以及所有 id 中的平均数“上传”action_type。所以想要的结果必须是这样的:

day     avg_num_action
0        2.5 
1        1.5

它是 2.5,因为 (3+2)/2(id:1 的 3 次上传和 id:2 的 2 次上传)。 1.5 相同

【问题讨论】:

  • MySQL 或 PostgreSQL 或 Presto?您使用的是哪个 DBMS?
  • @ThorstenKettner presto。但我对主要想法感兴趣
  • 我已更改标题以描述您想要的内容。通过描述问题,您会更接近解决方案。 “获取动作次数的平均值”:获取动作次数,然后获取它们的平均值。我在答案中显示的两个步骤。
  • 正如 Rahul Biswas 在他的回答中所表明的那样:您也可以用不同的方式描述问题。而不是您的描述 3 + 2(当天每个 ID 的操作数),您可以只说 5(当天的操作数)。因此,您会找到另一个更短更好的解决方案。
  • 给定查询的 select 语句中的列名后缺少逗号。

标签: sql presto


【解决方案1】:

更新:我认为我的两步法比需要的更复杂。 Rahul Biswas 展示了如何一步完成。我建议你使用并接受他的回答。


原答案:

两步:

  1. 按 ID 和日期计算条目数
  2. 获取每天的平均计数

查询:

with rows as (select id, date_diff('day', create_date, date) as day from mytable)
, per_id_and_day as (select id, day, count(*) as cnt from rows group by id, day)
select day, avg(cnt)
from per_id_and_day
group by day
order by day;

【讨论】:

    【解决方案2】:

    请试试这个。将您给定的查询视为一个表。如果需要任何 WHERE 条件,请启用此选项,否则禁用 where 子句。

    SELECT t.day
         , COUNT(*) / COUNT(DISTINCT t.id) avg_num_action
    FROM (SELECT id,
                date_diff("day", create_date, date) as day,
                action_type
          FROM "my_database") t
    WHERE t.action_type = 'upload'
    GROUP BY t.day
    

    根据给定的结果集创建一个表,并根据它编写查询。

    SELECT t.tday
         , COUNT(*) / COUNT(DISTINCT t.id) avg_num_action
    FROM my_database t
    GROUP BY t.tday
    

    请查看网址https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=871935ea2b919c4e24eb83fcbce78973

    【讨论】:

    • 它给出错误:不匹配的输入'*'
    • 请立即查看。
    • 请检查这个答案,如果有任何疑问,请告诉我。
    【解决方案3】:

    这个逻辑不需要子查询:

    SELECT date_diff("day", create_date, date) as day,
           COUNT(*) * 1.0 / COUNT(DISTINCT id)
    FROM "my_database"
    GROUP BY date_diff("day", create_date, date)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多