【问题标题】:550. Game Play Analysis IV - Why I cannot select from two tables?550. Game Play Analysis IV - 为什么我不能从两个表中选择?
【发布时间】:2022-01-22 13:12:07
【问题描述】:

#LC 550. 游戏玩法分析 IV


Column Name Type
player_id int
device_id int
event_date date
games_played int

(player_id, event_date) 是这个表的主键。 这张表显示了一些游戏玩家的活跃度。 每一行都是一个玩家的记录,该玩家在某天使用某些设备登录并玩了许多游戏(可能为 0 次)。

请求:编写 SQL 查询以报告在首次登录后的第二天再次登录的玩家比例,四舍五入到小数点后 2 位。换句话说,您需要计算从首次登录日期开始至少连续两天登录的玩家数量,然后将该数字除以玩家总数。

player_id device_id event_date games_played
1 2 2016-03-01 5
1 2 2016-03-02 6
2 3 2017-06-25 1
3 1 2016-03-02 0
3 4 2018-07-03 5
fraction
0.33

以下是我的代码(SQL Server):

with cte1 as (
    select a1.player_id as player_id
    from activity a1
    right join activity a2
    on dateadd(day, 1, a1.event_date) = a2.event_date
)


select round(count(distinct cte1.player_id)/count(distinct activity.player_id), 2) as fraction
from activity, cte1

结果应该是 0.33,但我得到了 0。可能是因为从两个表中选择(可以单独工作)。如果有人可以帮助我理解为什么它是错误的,我将不胜感激。非常感谢!

【问题讨论】:

  • Edit 问题并标记您正在使用的 DBMS。

标签: sql join rounding common-table-expression


【解决方案1】:

将其乘以 1.0 将自动将 count() (int) 转换为十进制。

select round(count(distinct cte1.player_id) * 1.0/count(distinct activity.player_id) * 1.0, 2) as fraction
from activity, cte1

【讨论】:

    【解决方案2】:

    你的尝试实际上并不算太远。

    当除法的所有操作数都是整数时,您的 DBMS 可能会进行整数除法。向上转换至少一个操作数,例如与1.0 相乘。

    但另外尝试左连接,这通常更容易理解和编写。您只需要一个连接,而您在 CTE 中加入 和 在外部 SELECT。

    还建议在FROM 子句中始终使用显式JOIN 语法而不是逗号。显式JOIN 语法通常更容易理解和编写而不会出错。

    SELECT round(count(DISTINCT a2.player_id) * 1.0
                 /
                 count(DISTINCT a1.player_id) * 1.0,
                 2) AS fraction
           FROM activity a1
                LEFT JOIN activity a2
                          ON a1.player_id = a2.player_id
                             AND a1.event_date = dateadd(day, -1, a2.event_date);
    

    db<>fiddle(假设是 SQL Server)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 2015-06-30
      • 2013-10-17
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多