相关文章推荐
阳刚的烤地瓜  ·  sql ...·  5 天前    · 
鼻子大的红金鱼  ·  hive 排序 ...·  4 天前    · 
大鼻子的奔马  ·  Android Studio - ...·  1 月前    · 
强健的烤面包  ·  【WinForm】Dev ...·  7 月前    · 
善良的麻辣香锅  ·  office ...·  1 年前    · 

计算两个不同的SQL查询结果的比率,返回数字

1 人不认可

我有查询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

mysql
sql
database
Umer Hayyat
Umer Hayyat
发布于 2022-02-05
1 个回答
Littlefoot
Littlefoot
发布于 2022-02-05
0 人赞同

如果你把这两个查询都作为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关键字;切换到两个子查询,然后;简化。

select a.value / b.value as result
from (select count(distinct user_id) value
from ... your 1st query goes here