2013-03-20 58 views
2

我有三个表,我提出的相同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

NO 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

如果你使用正确的语法为您的查询,然后将其MI在采访中,ght得到了进一步的发展。下面是该查询的版本,应该工作:

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(),正确的连接语法的,合理的别名。