我有一个数据库,其中包含不同客户的购买历史信息。我想要获得产品的项目对,这些产品是客户在一周内一起购买的,但不是在同一天。基本上,一个客户在周一来买了商品1和商品2,然后在周二回来买了商品3。我现在有关于哪个客户在什么日期购买了哪个商品的信息。每个事务都有自己的行。
最后,我想要两双: item 1& item 3和item2 & item3。为每一位顾客。
检查购买了item1 & item3的人是一回事,但检查是否在特定的时间范围内发生也让我苦苦挣扎。
数据位于Oracle数据库中。
感谢每一位的帮助!数据库和所需的结果大约如下所示:
发布于 2019-09-06 06:12:32
请在以后的问题中指出您的Oracle数据库的确切版本。
如果您使用的是12c或更高版本,“行模式匹配”就是为完成这类工作而设计的:
with data (customer, trans_date, purchase) as (
select 'C1', date '2019-08-01', 'Item1' from dual union all
select 'C1', date '2019-08-01', 'Item2' from dual union all
select 'C2', date '2019-08-01', 'Item4' from dual union all
select 'C2', date '2019-08-03', 'Item5' from dual union all
select 'C1', date '2019-08-04', 'Item3' from dual
)
select * from data
match_recognize(
partition by customer order by trans_date, purchase
measures first(trans_date) first_trans_date, first(purchase) first_purchase
all rows per match
after match skip to next row
pattern({-A+-} B+)
define a as trans_date = first(trans_date),
b as trans_date <= first(trans_date) + 7
);
CU TRANS_DATE PURCH FIRST_TRANS_DATE FIRST
-- ------------------- ----- ------------------- -----
C1 2019-08-04 00:00:00 Item3 2019-08-01 00:00:00 Item1
C1 2019-08-04 00:00:00 Item3 2019-08-01 00:00:00 Item2
C2 2019-08-03 00:00:00 Item5 2019-08-01 00:00:00 Item4
"A“行是在同一天购买的,"B”行是在那周晚些时候购买的。通过说“匹配后跳到下一行”,我可以一次处理多个"A“行。这比自连接要高效得多。
致以最好的问候,斯图·阿什顿
发布于 2019-09-06 00:13:23
您可以使用自联接:
with cid as (
select distinct customer, purchase, trunc(trans_date) as pdate
from t
)
select cid1.customer, cid1.item, cid2.item
from cid cid1 join
cid cid2
on cid1.customer = cid2.customer and
cid1.purchase <> cid2.purchase and
cid2.pdate > cid.pdate and
cid2.pdate < cid.pdate + interval '7' day;
这将按购买顺序返回项目。
https://stackoverflow.com/questions/57809346
复制相似问题