SQL query skills exclusive query is a customer who has used a certain item

Source: Internet
Author: User

The sales table is as follows:

Customer

Product

A

1

B

2

B

1

C

2

D

1

E

2

Ask the customer who has used only 2 products (no other products used) for exclusive Query

Table Structure

 

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'

Query;

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

Result

Customer times
---------------------
C 3
E 1

(Two rows have been processed successfully)

Other methods

 

Select customer,
Count (*) times
From @ TB
Where customer not in (select customer
From @ TB
Where product! = 2)
Group by customer

 

Organized from http://community.csdn.net/Expert/topic/5342/5342039.xml? Temp =. 7104914.

Thank you.Hhhdyj (Firefly)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.