我有两张桌子:
会话:此表包含用户拥有的所有会话。它包含3列。 uuid,user_id,happen_at
购买:此表包含用户所做的所有购买。它包含3列:purchase_id,user_id,buying_at
问题:对于每个会话,找到用户在会话时已经进行的购买数量
伪代码:
for session in sessions:
current_session_user_id = session["user_id"]
current_session_timestamp = session["occurred_at"]
num_purchases_made_at_the_time = query(
SELECT count(*) FROM purchases
WHERE
purchases.user_id = current_session_user_id
AND purchases.purchased_at < current_session_timestamp
)
注意:我的数据库(vertica)
不支持非相等相关子查询表达式一些想法,因为我无法使用相关子查询:
答案 0 :(得分:0)
你的意思是CTE作为公共表格表达还是...... CTE作为条件真实事件? : - )
如果你有:
SQL> select * from sessions order by uuid;
uuid | user_id | occurred_at
------+---------+---------------------
1 | 100 | 1959-03-07 04:31:15
2 | 100 | 1969-03-07 05:31:15
3 | 200 | 1979-03-07 06:31:15
4 | 200 | 1989-03-07 07:31:15
5 | 300 | 1999-03-07 08:31:15
和
SQL> select * from purchases order by purchase_id;
purchase_id | user_id | purchased_at
-------------+---------+---------------------
1000 | 100 | 1959-03-07 04:32:15
1001 | 100 | 1959-03-07 04:33:15
1002 | 100 | 1969-03-07 05:32:15
1003 | 200 | 1979-03-07 06:32:15
1004 | 300 | 1999-03-07 08:32:15
然后:
SQL> select max(a.user_id) as user_id, a.occurred_at, max(a.cte) as num_purchases
from ( select s.user_id, s.occurred_at,
conditional_true_event(purchased_at < occurred_at)
over(partition by s.user_id order by s.occurred_at) as cte
from purchases p inner join sessions s
on p.user_id = s.user_id
) a
group by a.occurred_at
order by 1, 2;
user_id | occurred_at | num_purchases
---------+---------------------+---------------
100 | 1959-03-07 04:31:15 | 0
100 | 1969-03-07 05:31:15 | 2
200 | 1979-03-07 06:31:15 | 0
200 | 1989-03-07 07:31:15 | 1
300 | 1999-03-07 08:31:15 | 0