SQL - 两个日期之间的条件
SQL - Conditions between 2 dates
我有一个包含 3 列的 table:user_id
、start_date
、cancellation_date
我想得到 4 列:
Date
、Number of Active Users
、Number of Users Who Canceled
、Cancellation Rate
关于如何编写查询的任何想法?
提前致谢!
如果我们将活跃用户定义为cancellation_date为空,查询将是这样的;
SELECT
( SELECT CURDATE() ) AS `DATE`,
( SELECT COUNT(*) FROM users WHERE cancellation_date IS NULL) AS `Number of active users`,
( SELECT COUNT(*) FROM users WHERE cancellation_date IS NOT NULL) AS `number of users who cancelled`,
( SELECT `number of users who cancelled` / (`Number of active users` + `number of users who cancelled`)) AS `cancellation rate`
测试于 MySQL 8,https://www.db-fiddle.com/f/6QPLn2C79rnzrfN71i1GMV/0
这是衡量新用户、取消用户、活跃用户的方法:
SELECT calendar_date,
(SELECT COUNT(*) FROM users AS usr WHERE cal.calendar_date BETWEEN usr.start_date AND IFNULL(usr.cancellation_date, '3000-01-01')) AS active_users,
(SELECT COUNT(*) FROM users AS usr WHERE usr.start_date = cal.calendar_date) AS new_users,
(SELECT COUNT(*) FROM users AS usr WHERE usr.cancellation_date = cal.calendar_date) AS users_cancelled
FROM my_calendar AS cal
(假设您有 table "my_calendar" 其中包含所有日期)
我有一个包含 3 列的 table:user_id
、start_date
、cancellation_date
我想得到 4 列:
Date
、Number of Active Users
、Number of Users Who Canceled
、Cancellation Rate
关于如何编写查询的任何想法?
提前致谢!
如果我们将活跃用户定义为cancellation_date为空,查询将是这样的;
SELECT
( SELECT CURDATE() ) AS `DATE`,
( SELECT COUNT(*) FROM users WHERE cancellation_date IS NULL) AS `Number of active users`,
( SELECT COUNT(*) FROM users WHERE cancellation_date IS NOT NULL) AS `number of users who cancelled`,
( SELECT `number of users who cancelled` / (`Number of active users` + `number of users who cancelled`)) AS `cancellation rate`
测试于 MySQL 8,https://www.db-fiddle.com/f/6QPLn2C79rnzrfN71i1GMV/0
这是衡量新用户、取消用户、活跃用户的方法:
SELECT calendar_date,
(SELECT COUNT(*) FROM users AS usr WHERE cal.calendar_date BETWEEN usr.start_date AND IFNULL(usr.cancellation_date, '3000-01-01')) AS active_users,
(SELECT COUNT(*) FROM users AS usr WHERE usr.start_date = cal.calendar_date) AS new_users,
(SELECT COUNT(*) FROM users AS usr WHERE usr.cancellation_date = cal.calendar_date) AS users_cancelled
FROM my_calendar AS cal
(假设您有 table "my_calendar" 其中包含所有日期)