复杂 SQL 查询问题
Complex SQL query Issues
我在 select 从 table 获取数据时遇到问题。我敢肯定答案就在我眼前,但我的大脑一片糊涂。我们正试图仅根据电子邮件群发而不是其他任何因素来找出哪些客户购买了产品。我可以轻松地 select 任何 salesPrompt
= 'email' 的行,但这可能仍然包括由于 salesPrompt
= 'postcard' 或其他一些方法而购买的人。我如何 select 只有因电子邮件爆炸而购买的客户?我试过:
SELECT * FROM `customer_sales` WHERE `salesPrompt` = 'email' GROUP BY `accountID`
但这仍然会带来 salesPrompt
等于其他值的客户。
您应该使用 having 检查 count distinct sale Prompt 并加入结果
select s.*
FROM `customer_sales`
inner join (
SELECT accountID
FROM `customer_sales`
GROUP BY `accountID`
having count(distinct salesPrompt) = 1
) t on t.accountID = s.accountID
where `salesPrompt` = 'email'
另一种可能性是 select 所有具有所需 salesPrompt 的条目,然后排除(使用 EXISTS)所有具有更多 salesPrompts 和相同帐户 ID 的条目。假设,您想将主要 selection 命名为“target”,如下所示:
SELECT salesprompt, accountid
FROM customer_sales AS target WHERE salesprompt = 'email'
AND NOT EXISTS (SELECT 1 FROM customer_sales WHERE salesprompt != 'email'
AND accountid = target.accountid);
我在 select 从 table 获取数据时遇到问题。我敢肯定答案就在我眼前,但我的大脑一片糊涂。我们正试图仅根据电子邮件群发而不是其他任何因素来找出哪些客户购买了产品。我可以轻松地 select 任何 salesPrompt
= 'email' 的行,但这可能仍然包括由于 salesPrompt
= 'postcard' 或其他一些方法而购买的人。我如何 select 只有因电子邮件爆炸而购买的客户?我试过:
SELECT * FROM `customer_sales` WHERE `salesPrompt` = 'email' GROUP BY `accountID`
但这仍然会带来 salesPrompt
等于其他值的客户。
您应该使用 having 检查 count distinct sale Prompt 并加入结果
select s.*
FROM `customer_sales`
inner join (
SELECT accountID
FROM `customer_sales`
GROUP BY `accountID`
having count(distinct salesPrompt) = 1
) t on t.accountID = s.accountID
where `salesPrompt` = 'email'
另一种可能性是 select 所有具有所需 salesPrompt 的条目,然后排除(使用 EXISTS)所有具有更多 salesPrompts 和相同帐户 ID 的条目。假设,您想将主要 selection 命名为“target”,如下所示:
SELECT salesprompt, accountid
FROM customer_sales AS target WHERE salesprompt = 'email'
AND NOT EXISTS (SELECT 1 FROM customer_sales WHERE salesprompt != 'email'
AND accountid = target.accountid);