![](/img/trans.png)
[英]Select all customer who have bought 'x' times something from the category 'y' within the last 'z' days
[英]list of those Customer IDs from Table X who have bought all of the products from Table Y?
我有2个表X和Y,
表X (有5条记录)
Cust_Id Prod_Key
1 'A'
1 'D'
2 'C'
3 'D'
2 'B'
表Y (有2条记录)
Prod_Key
'A'
'D'
需要SQL列出具有表Y中所有产品的Cust_ID。〜由于表不断更新,无法硬编码
您可以尝试以下方法:
select
cust_id
from
Y
LEFT OUTER JOIN
X
on Y.Prod_key = X.Prod_key
Group by
Cust_id
having
count(DISTINCT X.Prod_key) = (select count(*) from Y);
您可以将INNER JOIN
与GROUP BY
和COUNT
,如下所示
SELECT x.Cust_Id
FROM X x
INNER JOIN Y y ON y.Prod_Key = x.Prod_Key
GROUP BY x.Cust_Id
HAVING COUNT(y.Prod_Key) = (SELECT COUNT(*) FROM Y)
您可以尝试以下代码来获取Cust_ID的唯一列表
select DISTINCT Cust_Id from X where x.Prod_key in (select y.Prod_key from Y)
您也可以尝试内部productkey
因为只需要其产品productkey
在表y中存在的customerid
SELECT x.Cust_Id
FROM x
INNER JOIN y
ON x.Prod_Key = y.Prod_key
尝试这个 :
从x中选择*,其中prod_key位于(从Y中选择prod_key)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.