我有查询1
SELECT COUNT(DISTINCT user_id) total_daily_active_user_group_month FROM (SELECT user_id , MONTHNAME(time) mon , COUNT(*) cnt FROM ACTIVITIES
WHERE MONTH(time) = MONTH(NOW() - INTERVAL 1 MONTH) GROUP by user_id, MONTH(time) ) as x
返回 18
SELECT COUNT(DISTINCT user_id) total_daily_active_user_group_month FROM (SELECT user_id , MONTHNAME(time) mon , COUNT(*) cnt FROM ACTIVITIES
WHERE MONTH(time) = MONTH(NOW() - INTERVAL 1 MONTH) GROUP by user_id, MONTH(time) having cnt=31) as x
我想要查询1和2的比例。手段
18/6 .我正在使用MySQL
如果你把这两个查询都作为CTE使用,那么它就变得相对简单了。
WITH q1 AS (SELECT Count(DISTINCT user_id) total_daily_active_user_group_month FROM (SELECT user_id, Monthname(TIME) mon, Count(*) cnt FROM activities WHERE Month(TIME) = Month(Now() - interval 1 month) GROUP BY user_id, Month(TIME))), AS (SELECT Count(DISTINCT user_id) total_daily_active_user_group_month FROM (SELECT user_id, Monthname(TIME) mon, Count(*) cnt FROM activities WHERE Month(TIME) = Month(Now() - interval 1 month) GROUP BY user_id, Month(TIME) HAVING cnt = 31)) SELECT q1.total_daily_active_user_group_month / q2.total_daily_active_user_group_month AS result FROM dual;
你评论说,你得到一个错误,指向
关键字;切换到两个子查询,然后;简化。WITH