我有一个餐桌订单,上面有关于下订单的时间以及下订单的人的信息。
order_timestamp user_id
-------------------- ---------
1-JAN-20 02.56.12 123
3-JAN-20 12.01.01 533
23-JAN-20 08.42.18 123
12-JAN-20 02.53.59 238
19-JAN-20 02.33.72 34
我想使用此信息每天计算在过去31天中只下过一次订单的不重复用户数,得出的表为
date distinct_user_count
----------- ---------------------
1-JAN-20 8
2-JAN-20 10
3-JAN-20 11
(i.e in the 31 days before and including 1st jan 2020, 8 unique users ordered only once, etc...)
简单地说,每天-31,计算该时段内每个用户的订单数(表中的条目),如果该计数仅为1,则将该用户计为初始开始日期。
我可以编写查询来将仅订购一次的人计数为:
with temp as (
select
user_id,
count(*) as order_count
from
orders
where
trunc(order_timestamp) >= trunc(systimestamp - interval '31' day)
group by
user_id
)
select
user_id,
order_count
from
temp
where
login_count=1
,但不确定如何实施每个日期的计数。请您协助我完成/撰写查询吗?感谢您的预先支持。
答案 0 :(得分:0)
您可以使用grouping
和self join
这两个级别,如下所示:
Select dt, count(1) as cnt
from
(Select distinct trunc(t1.order_timestamp) as dt,
t1.user_id
From your_table t1
join your_table t2
On t1.user_id = t2.user_id
And trunc(t2.order_timestamp) between trunc(t1.order_timestamp - interval '31' day)
and trunc(t1.order_timestamp)
Group by t1.user_id, trunc(t1.order_timestamp)
Having count(1) = 1)
Group by dt;
或者您可以按以下方式使用NOT EXISTS
:
Select trunc(t1.order_timestamp),
Count(1) as cnt
From your_table t1
Where not exists
(Select 1
From your_table t2
Where t1.rowid <> t2.row_id
And t1.user_id = t2.user_id
And trunc(t2.order_timestamp) between trunc(t1.order_timestamp - interval '31' day)
and trunc(t1.order_timestamp)
Group by trunc(t1.order_timestamp)