我的表格包含customer_id
和product_id
customer_id product_id
c1 1
c1 2
c1 3
c2 1
c2 2
c2 3
c3 5
c4 5
c5 3
我需要过滤相同数量的带来相同数量产品的客户。
除此之外,客户(c5,3)无效,因为他有相同的product_id但记录数量与客户不匹配。
这是我试过的查询
SELECT T1.ORDER_ID FROM @ORDER T1
WHERE EXISTS (SELECT * FROM @ORDER T2
WHERE T2.PRODUCT_ID = T1.PRODUCT_ID
AND T2.ORDER_ID != T1.ORDER_ID
GROUP BY T2.ORDER_ID)
输出应该是这样的
customer_id product_id
customer_id product_id
c1 1
c1 2
c1 3
c2 1
c2 2
c2 3
c3 5
c4 5
答案 0 :(得分:0)
我尝试了以下方法,看看它是否也适用于您的情况。它似乎不是最好的解决方案,但它确实有效。
<强> TEST_DROP1:强>
cust_id Prod_id
C1 1
C1 2
C1 3
C2 1
C2 2
C2 3
C3 5
C4 5
C5 3
<强>解决方案:强>
第1步:
CREATE TABLE TEST_DROP2 AS
SELECT CUST_ID,
LISTAGG(PRODUCT_ID, ',') WITHIN GROUP (
ORDER BY PRODUCT_ID) prods
FROM TEST_DROP1
GROUP BY CUST_ID;
TEST_DROP2:
cust_id prod_id
C1 1,2,3
C2 1,2,3
C3 5
C4 5
C5 3
运行以下查询,
SELECT *
FROM TEST_DROP1
WHERE cust_id IN
(SELECT CUST_ID
FROM TEST_DROP2
WHERE PRODS IN
( SELECT PRODS FROM TEST_DROP2 GROUP BY PRODS HAVING COUNT(1)>1
)
)
ORDER BY CUST_ID,
product_id;**
结果:
C1 1
C1 2
C1 3
C2 1
C2 2
C2 3
C3 5
C4 5