SQL Server SQL计算分数升级率

jtoj6r0c  于 2022-11-21  发布在  其他
关注(0)|答案(2)|浏览(129)

给定以下两个表
使用者

user_id name    join_date
1       Jon     2020-02-14
2       Jane    2020-02-14
3       Jill    2020-02-15
4       Josh    2020-02-15
5       Jean    2020-02-16
6       Justin  2020-02-17
7       Jeremy  2020-02-18

事件

user_id type access_date
1       F1   2020-03-01
2       F2   2020-03-02
2       P    2020-03-12
3       F2   2020-03-15
4       F2   2020-03-15
1       P    2020-03-16
3       P    2020-03-22

返回访问功能2(类型:F2),并在注册后的前30天内升级到高级版。它应该给予upgrade_rate 0.33。
这是我的尝试

;WITH users AS (
  SELECT * FROM (
    VALUES
        (1, 'Jon', CAST('14-02-20' AS date)), 
        (2, 'Jane', CAST('14-02-20' AS date)), 
        (3, 'Jill', CAST('15-02-20' AS date)), 
        (4, 'Josh', CAST('15-02-20' AS date)), 
        (5, 'Jean', CAST('16-02-20' AS date)), 
        (6, 'Justin', CAST('17-02-20' AS date)),
        (7, 'Jeremy', CAST('18-02-20' AS date))
  ) AS _ (user_id, name, join_date)
),
events AS (
  SELECT * FROM (
    VALUES
        (1, 'F1', CAST('01-03-20' AS date)),
        (2, 'F2', CAST('02-03-20' AS date)), 
        (2, 'P', CAST('12-03-20' AS date)),
        (3, 'F2', CAST('15-03-20' AS date)), 
        (4, 'F2', CAST('15-03-20' AS date)), 
        (1, 'P', CAST('16-03-20' AS date)), 
        (3, 'P', CAST('22-03-20' AS date))
  ) AS _ (user_id, type, access_date)
),
feature_two_upg AS (
    SELECT * 
    FROM events
    WHERE type = 'F2'
),
premium_upg AS (
    SELECT *
    FROM events
    WHERE type = 'P'
),
differ_date AS (
    SELECT feature.user_id, premium.access_date
    FROM feature_two_upg AS feature
    INNER JOIN premium_upg AS premium
    ON feature.user_id = premium.user_id
    WHERE DATEDIFF(DAY, feature.access_date, premium.access_date) < 30
)

SELECT ROUND(AVG(CAST(CASE WHEN differ_date.user_id IS NOT NULL THEN 1.0 ELSE 0.0 END AS float)), 2) AS upgrade_rate
FROM users
LEFT JOIN differ_date
ON users.user_id = differ_date.user_id

现在它给我0.29升级率,我想知道为什么

amrnrhlw

amrnrhlw1#

现在,我来检查一下您的查询,让我们显示一下表中没有函数的结果

SELECT users.user_id, differ_date.user_id
FROM users
LEFT JOIN differ_date
ON users.user_id = differ_date.user_id

结果是这样的

users.user_id   differ_date.user_id
1                 NULL
2                   2
3                   3
4                  NULL
5                  NULL
6                  NULL
7                  NULL

现在检查您的公式,每次diffect_date.user_id不为空时,您将求和1,然后函数avg计算7寄存器,结果为2 / 7 = 0.28571428,舍入为2 =0.29
此致

xtfmy6hx

xtfmy6hx2#

当我运行这个函数时,得到的结果是0.00,除非我在diffect_date中注解掉WHERE DATEDIFF(DAY,feature.access_date,premium.access_date)〈30,否则得到的结果是0.29。

相关问题