您的位置:首页 > 数据库

SQL学习之查询技巧 排他查询 只是用过某商品的顾客

2007-02-08 15:25 453 查看
销售表如下

customer
product
A
1
B
2
B
1
C
2
D
1
E
2
求只使用过2产品的顾客( 没有使用过其他产品) 排他查询

表结构

 


DECLARE @tb TABLE([customer] varchar(10), [product] varchar(10))


INSERT INTO @tb


    SELECT  'A', '1'


    UNION ALL SELECT 'B', '2'


    UNION ALL SELECT 'B', '1'


    UNION ALL SELECT 'C', '2'


    UNION ALL SELECT 'C', '2'


    UNION ALL SELECT 'D', '1'


    UNION ALL SELECT 'E', '2'


    UNION ALL SELECT 'C', '2'

查询;


SELECT   customer,


         Count(product)  times


FROM     @tb t


WHERE    EXISTS (SELECT 1


                 FROM   @tb


                 WHERE  customer = t.customer


                        AND product = 2)


GROUP BY customer


HAVING   Count(DISTINCT product) = 1




结果


customer   times


---------- -----------


C          3


E          1




(2 行処理されました)



其他方法

 


SELECT   customer,


         Count(* ) times


FROM     @tb


WHERE    customer NOT IN (SELECT customer


                          FROM   @tb


                          WHERE  product != 2)


GROUP BY customer

 

整理自http://community.csdn.net/Expert/topic/5342/5342039.xml?temp=.7104914

谢谢hhhdyj(萤火虫)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sql insert 产品 table c