SQL否定查询

时间:2013-03-20 14:04:17

标签: sql

我有三张桌子,我正在展示相同的简化版本

CUSTOMER_DIM

[Cust_id] [Cust_Name]

PRODUCT_DIM

[Prod_id] [Prod_Name]

Orders_fact

[ord_id] [Cust_id] [Prod_id]

我希望所有购买过每件产品的顾客(甚至没有一件产品都缺失)

我想要一个更优雅的查询,而不仅仅是将每个客户群的数量等同于prod_dim的总数

即。我不想要下面的问题(因为这是一个面试问题,也有优雅的要点)

select cust_name 
from customers c, 
   (select cust_id, count(prod_id) cnt 
    from order_fact 
    group by cust_id where cnt = (select count(prod_id) from prod_dim)) t1
where c.cust_id = t1.cust_id

2 个答案:

答案 0 :(得分:2)

countgroup by版本:

SELECT Cust_Name FROM Customer_dim WHERE Cust_Id NOT IN (
    SELECT c.Cust_Id FROM Product_dim p
    CROSS JOIN Customer_dim c 
    LEFT JOIN Orders_fact o ON o.Prod_Id = p.Prod_Id AND c.Cust_Id = o.Cust_Id
    WHERE Ord_Id IS NULL
)

答案 1 :(得分:1)

如果您的查询使用了正确的语法,那么它可能在访谈中得到了进一步的发展。以下是应该有效的查询版本:

select c.cust_name 
from customers c join
     (select ofa.cust_id 
      from order_fact ofa
      group by ofa.cust_id 
      having cnt = (select count(distinct prod_id) from prod_dim)
     ) ccnt
     on c.cust_id = ccnt.cust_id

请注意having子句count(distinct)而不是count()使用正确的连接语法和合理的别名。