查找客户一起购买但不重复的产品列
Find Products customer bought together but non repeating columns
我正在使用 SQL 服务器,我试图找出一起购买最多的前 2 种产品
这是一个产品table
我希望它显示如下图:
我试过了
SELECT TOP 2 Product_Id, bought_with_Product_Id, times_bought_together
FROM PRODUCT
GROUP BY Product_Id, bought_with_Product_Id, times_bought_together
也试过了
SELECT TOP 2 *
FROM Product
WHERE times_bought_together = (SELECT MAX(times_bought_together) FROM product)
AND Product_Id <> bought_with_Product_Id
它returns
如何才能使 product_id 和 bought_with_product_Id 行不重叠
您可以使用 NOT EXISTS
测试排除重复行,例如
declare @Test table (id int, otherId int, times int);
insert into @Test (id, otherId, times)
values
(1,2,3),
(2,1,3),
(4,1,2),
(1,4,2),
(1,5,1),
(5,1,1);
select top 2 *
from @Test T1
where not exists (
select 1
from @Test T2
where T1.id = T2.otherId
and T1.otherId = T2.id
-- Keep the duplicate with the lower id
and T2.id < T1.id
);
Returns:
id
otherId
times
1
2
3
1
4
2
注意:为您的测试数据提供 DDL+DML(如此处所示)可以让人们更容易回答您的问题。
我正在使用 SQL 服务器,我试图找出一起购买最多的前 2 种产品
这是一个产品table
我希望它显示如下图:
我试过了
SELECT TOP 2 Product_Id, bought_with_Product_Id, times_bought_together
FROM PRODUCT
GROUP BY Product_Id, bought_with_Product_Id, times_bought_together
也试过了
SELECT TOP 2 *
FROM Product
WHERE times_bought_together = (SELECT MAX(times_bought_together) FROM product)
AND Product_Id <> bought_with_Product_Id
它returns
如何才能使 product_id 和 bought_with_product_Id 行不重叠
您可以使用 NOT EXISTS
测试排除重复行,例如
declare @Test table (id int, otherId int, times int);
insert into @Test (id, otherId, times)
values
(1,2,3),
(2,1,3),
(4,1,2),
(1,4,2),
(1,5,1),
(5,1,1);
select top 2 *
from @Test T1
where not exists (
select 1
from @Test T2
where T1.id = T2.otherId
and T1.otherId = T2.id
-- Keep the duplicate with the lower id
and T2.id < T1.id
);
Returns:
id | otherId | times |
---|---|---|
1 | 2 | 3 |
1 | 4 | 2 |
注意:为您的测试数据提供 DDL+DML(如此处所示)可以让人们更容易回答您的问题。