我有3个表(用户,答案和问题),需要计算已注册且未注册且已完成每天所有答案的用户总数。
所以我会有类似的东西:
第1天完成的总用户数,第1天完成的注册用户总数
第2天完成的总用户数,第2天完成的注册用户总数
第3天完成的总用户数,第3天完成的注册用户总数
表结构是:
Users
Id, registered
Answers
id, user_id, question_id
Questions
id, day
这是我正在使用的查询。
select
a.user_id, a.question_id ,
count(distinct q.day) as day
from answers a
left join questions q on q.id = a.question_id
left join users u on u.registered IS NOT NULL
group by u.id
答案 0 :(得分:1)
尝试这样的事情:
SELECT q.day, COUNT(u.id) AS users, COUNT(u.registered) AS reg_users
FROM answers a
JOIN questions q ON q.id = a.question_id
JOIN users u ON u.id = a.user_id
GROUP BY q.day
如果您一天中有多个用户,您应该尝试这样的事情:
SELECT day, COUNT(id) AS users, COUNT(registered) AS reg_users
FROM ( SELECT DISTINCT q.day, u.id, u.registered
FROM answers a
JOIN questions q ON q.id = a.question_id
JOIN users u ON u.id = a.user_id ) qwert
GROUP BY day
对在给定日期至少回答了15个问题的用户进行计数:
SELECT day, user_id, COUNT( DISTINCT question_id) AS users_15
FROM answers a
JOIN questions q ON q.id = a.question_id
GROUP BY day, user_id
HAVING COUNT( DISTINCT question_id) >= 15