【发布时间】:2019-09-11 02:30:57
【问题描述】:
给定下表:
transaction_id user_id product_id
1 10 AA
2 10 CC
3 10 AA
4 10 CC
5 20 AA
6 20 BB
7 20 BB
8 30 BB
9 30 BB
10 30 BB
11 40 CC
12 40 AA
13 40 CC
14 40 BB
15 40 BB
16 50 EE
17 60 EE
使用以下查询:
select
product_id,
count(distinct user_id) as count_repeat_users
from
product_usage_log
where
(product_id, user_id) in (
select
product_id,
user_id
from (
select
product_id,
user_id,
count (distinct transaction_id) as transactions
from
product_usage_log
group by
product_id,
user_id
) t
where transactions >= 2
)
group by product_id
返回以下结果:
product_id count_repeat_users
AA 1
BB 3
CC 2
(note that 'EE' doesn't appear, as expected)
上述查询的目的是为每个产品返回至少与该产品进行过两次交易的用户计数。上面的查询满足了这一点,但是它使用了一个带有IN 谓词的多列子查询。此功能在 Presto 中不可用(虽然过去两年一直在讨论但没有成功)。
如果无法使用where (product_id, user_id) in (...),如何复制上述结果?
注意:我尝试将where 条件展平为两个连续的条件,问题是现在所有列匹配每一行的条件变成所有列匹配任何行的条件。换句话说,现在只要产品在子表中,它就会匹配用户-产品对,并且用户在子表中,但不一定在同一行。
因此,另一种表述问题的方式是:在 Presto 中,如何根据子查询中 SAME 行中存在的几个值来创建条件?
【问题讨论】: