我有一个包含这些表的数据库
employees(eid, name, telephone#, email)
customers(cid, name, telephone#, visits_made, last_visit_date)
products(pid, name, qoh, qoh_threshold, original_price, discnt_rate)
purchases(pur#, eid, pid, cid, ptime, qty, total_price)
我试图找到2017年10月访问过零售业务的每位客户的CID,并购买了所有原价超过200美元的产品。
下面的查询会产生正确的CID,但似乎是出于错误的原因。
SELECT cid
FROM purchases pur
INNER JOIN (SELECT pro.pid
FROM products pro
INNER JOIN purchases pur
ON pro.pid = pur.pid
WHERE original_price > 200) t
ON pur.pid = t.pid
WHERE to_char(ptime, 'MM/YYYY') = '10/2017'
GROUP BY cid
我相信这是在2017年10月找到所有使用original_price > 200
购买产品的客户。我最初的想法是使用ALL()
,但我也没有任何运气。
答案 0 :(得分:1)
SELECT cid
FROM purchases pur
WHERE to_char(ptime, 'MM/YYYY') = '10/2017'
AND pid IN (
SELECT pid FROM products WHERE original_price > 200
)
GROUP BY cid,pid
HAVING COUNT(1) = (SELECT COUNT(pid) FROM products WHERE original_price > 200)
答案 1 :(得分:1)
到目前为止,我知道你想要这样的查询 -
select pur.cid
from purchases pur
join products pro
on pur.pid = pro.pid
where pro.original_price > 200
and month(pur.ptime) = 10
group by pur.cid;
<强>更新强>
您可以尝试此查询。这可能满足您的需求,虽然我没有使用填充数据进行测试。
SELECT temp.cid,
COUNT ( * ) no_of_product
FROM (
SELECT
p.cid,
pt.original_price
FROM
( SELECT cid,pid FROM
PURCHASES
GROUP BY cid, pid
) p
INNER JOIN
(
SELECT
pid,
original_price
FROM
product
WHERE
original_price > 200
) pt
p.pid = pt.pid
) temp
GROUP BY temp.cid
having count(*) > (select count(*) from product where original_price > 200) - 1 ;
答案 2 :(得分:0)
所以,在阅读了其他一些材料并尝试了一些不同的东西后,我想我的查询是正确的。这似乎是一个可以通过关系划分解决的查询,并且通过利用嵌套的NOT EXISTS
查询实现这一目标的一种方法。 This article讨论了在SQL中非常详细地执行关系划分,并帮助我清理了很多东西,所以对于那些有类似查询的人来说,阅读那篇文章。
以下是我认为现在正常运行的查询
SELECT c.cid
FROM customers c
INNER JOIN purchases pur
ON c.cid = pur.cid
WHERE to_char(ptime, 'MM/YYYY') = '10/2017'
AND NOT EXISTS (SELECT *
FROM products pro
WHERE pid IN (SELECT pro.pid
FROM products pro
WHERE original_price > 200)
AND NOT EXISTS (SELECT *
FROM purchases pur
WHERE pur.cid = c.cid
AND pur.pid = pro.pid))