我有一个有3个表的数据库:队列时间段,用户和事件。
队列有很多用户,每个用户有很多事件。队列也有与之相关的时间段。我想知道每个队列,每个时间段发生了多少事件。
如果有两个表,那么做一个CROSS JOIN会很容易,但是当有这个中间表时,我就卡住了。
下面是DB结构:
create table time_periods (
cohort_name varchar,
period_name varchar,
start_time timestamp,
end_time timestamp);
create table users (
cohort_name varchar,
user_name varchar
);
create table events (
user_name varchar,
ts timestamp);
insert into time_periods values
('cohort1', 'first', '2017-01-01', '2017-01-10'),
('cohort1', 'second', '2017-01-10', '2017-01-20'),
('cohort2', 'first', '2017-01-15', '2017-01-20');
insert into users values
('cohort1', 'alice'),
('cohort2', 'bob');
insert into events values
('alice', '2017-01-07'),
('alice', '2017-01-17'),
('bob', '2017-01-18');这是我对SQL所能得到的最大结果-执行一个三重交叉连接,但这是不正确的-结果是6个事件,而实际上应该是每行1个事件。
select
time_periods.cohort_name,
period_name,
count(ts)
from time_periods, users, events
group by 1, 2
order by time_periods.cohort_name下面是SQLFiddle:
http://sqlfiddle.com/#!17/b141e/2
发布于 2017-08-16 22:53:54
您需要指定要在哪些列上连接表,如果我正确理解了您的数据,您需要如下所示:
select
tp.cohort_name,
tp.period_name,
count(*)
from time_periods tp
inner join users u on tp.cohort_name = u.cohort_name
inner join events e on u.user_name = e.user_name and e.ts between tp.start_time and tp.end_time
group by 1, 2
order by tp.cohort_name在这里,您仅针对正确队列中的用户从time_periods加入到users,然后仅针对特定时间段内的指定用户和事件加入到events,然后按1和2分组以获得正确的偶数计数
https://stackoverflow.com/questions/45716679
复制相似问题