我有一個包含兩列的表:ProductID 和 CustomerID
每次特定客戶 (CustomerID) 購買特定產品(由特定 ProductID 表示)時,該表都會記錄該情況。
ProductID 可以出現多次,與不同的 customerID 匹配(并且客戶可能多次購買產品)。
| 產品編號 | 顧客ID |
|---|---|
| 1111111 | 14567 |
| 2222222 | 17890 |
| 3333333 | 17890 |
| 4444444 | 17890 |
| 5555555 | 14567 |
| 5555555 | 17890 |
有沒有辦法將購買了某種產品(ProductID)但沒有購買另一種產品(ProductID)的客戶(CustomerID)拉出來。
目前,我有
select a.CustomerID
from iread a, iread b
where a.CustomerID in ({{ProductID}}) and b.CustomerID not in ({{ProductID}})
and a.CustomerID=b.CustomerID
這只是給了我 ProductID 回來......我認為這可能與這部分有關:
where a.CustomerID in ({{ProductID}}) and b.CustomerID not in ({{ProductID}})
歡迎任何幫助/解決方案!謝謝!!
uj5u.com熱心網友回復:
使用 having 子句和 case 運算式來過濾聚合記錄將幫助您跨多行進行過濾。這也比自聯接便宜。
例如
SELECT
CustomerID
FROM
iread
WHERE
ProductID IN (<included_comma_separated_product_ids_to_be_considered_which_are_desired_and_not_desired>)
GROUP BY
CustomerID
HAVING
SUM(
CASE WHEN ProductID=<include_desired_product_id> THEN 1 ELSE 0 END
) > 0 AND
SUM(
CASE WHEN ProductID=<include_not_desired_product_id> THEN 1 ELSE 0 END
) = 0
下面是一個示例,我們嘗試根據您共享的示例資料查找購買5555555但不購買的客戶1111111。
用于除錯目的的聚合結果
SELECT
CustomerID,
SUM(
CASE WHEN ProductID=5555555 THEN 1 ELSE 0 END
) as desired_product,
SUM(
CASE WHEN ProductID=1111111 THEN 1 ELSE 0 END
) as undesired_product
FROM
iread
WHERE
ProductID IN (5555555,1111111)
GROUP BY
CustomerID;
| 顧客ID | 期望的產品 | 不想要的_產品 |
|---|---|---|
| 14567 | 1 | 1 |
| 17890 | 1 | 0 |
使用 Have 和 Case 運算式來檢索所需的客戶
SELECT
CustomerID
FROM
iread
WHERE
ProductID IN (5555555,1111111)
GROUP BY
CustomerID
HAVING
SUM(
CASE WHEN ProductID=5555555 THEN 1 ELSE 0 END
) > 0 AND
SUM(
CASE WHEN ProductID=1111111 THEN 1 ELSE 0 END
) = 0;
| 顧客ID |
|---|
| 17890 |
查看 DB Fiddle 上的作業演示
Edit 1: I have modified the examples above to include a where clause. This should take advantage of indexes on the columns used in the where clause if indexes are available on the table.
Let me know if this works for you.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/328334.html
上一篇:[回傳結果不正確]AWSRedshift(RedShift)中Join陳述句的限制不正確
下一篇:針對自身的過濾版本加入資料幀
