如何查询显示客户在同一天的购买情况,但前提是这些是在不同的商店 (oracle) 进行的?

How to make a query showing purchases of a client on the same day, but only if those were made in diffrent stores (oracle)?

我想展示在同一天至少购买了 2 件商品的客户案例。但我只想计算那些在不同商店进行的购买。 到目前为止我有:

Select Purchase.PurClientId, Purchase.PurDate, Purchase.PurId
from Purchase  
join 
( 
 Select count(Purchase.PurId), 
   Purchase.PurClientId, 
   to_date(Purchase.PurDate)
 from Purchases
 group by Purchase.PurClientId, 
      to_date(Purchase.PurDate)
 having count (Purchase.PurId) >=2 
 ) k 
    on k.PurClientId=Purchase.PurClientId

但我不知道如何让它只计算在不同商店购买的商品。允许识别商店的列是 Purchase.PurShopId。 感谢您的帮助!

您可以使用:

SELECT PurId,
       PurDate,
       PurClientId,
       PurShopId
FROM   (
  SELECT p.*,
         COUNT(DISTINCT PurShopId) OVER (
           PARTITION BY PurClientId, TRUNC(PurDate)
         ) AS num_stores
  FROM   Purchase p
)
WHERE  num_stores >= 2;

SELECT *
FROM   Purchase p
WHERE  EXISTS(
  SELECT 1
  FROM   Purchase x
  WHERE  p.purclientid = x.purclientid
  AND    p.purshopid != x.purshopid
  AND    TRUNC(p.purdate) = TRUNC(x.purdate)
);

其中,对于示例数据:

CREATE TABLE purchase (
  purid PRIMARY KEY,
  purdate,
  purclientid,
  PurShopId
) AS
SELECT 1, DATE '2021-01-01', 1, 1 FROM DUAL UNION ALL
SELECT 2, DATE '2021-01-02', 1, 1 FROM DUAL UNION ALL
SELECT 3, DATE '2021-01-02', 1, 2 FROM DUAL UNION ALL
SELECT 4, DATE '2021-01-03', 1, 1 FROM DUAL UNION ALL
SELECT 5, DATE '2021-01-03', 1, 1 FROM DUAL UNION ALL
SELECT 6, DATE '2021-01-04', 1, 2 FROM DUAL;

双输出:

PURID PURDATE PURCLIENTID PURSHOPID
2 2021-01-02 00:00:00 1 1
3 2021-01-02 00:00:00 1 2

db<>fiddle here