SQL查询以显示已购买某些特定产品的客户的名称

时间:2018-07-28 18:24:53

标签: sql sql-server database relational-database

这些是我创建的表,并相应地插入了值:

CREATE TABLE Customer
(
     Customer_Id INTEGER IDENTITY (1,1) PRIMARY KEY,
     Customer_Name VARCHAR(30) NOT NULL
)

CREATE TABLE Product
(
     Product_Id INTEGER IDENTITY (1,1) PRIMARY KEY,
     Product_Name VARCHAR(30)
)

CREATE TABLE Product_Purchase
(
     Purchase_Id INTEGER IDENTITY (1,1) PRIMARY KEY,
     Product_Id INTEGER NOT NULL,
     Customer_Id INTEGER NOT NULL
 )

INSERT INTO Customer (Customer_Name)
VALUES ('Sandip'), ('Ankit'), ('Ashok'), ('Raj')

INSERT INTO Product (Product_Name)
VALUES ('Milk'), ('Egg'), ('Butter'), ('Paneer'), ('Curd')

INSERT INTO Product_Purchase (Product_Id, Customer_Id)
VALUES (4, 1), (1, 1), (3, 1)
       (4, 2), (1, 2), 
       (4, 3), (3, 3), (1, 3),
       (1, 4), (2, 4), (3, 4), (4, 4)

所以我有3个表Customer,Product和Product_Purchase,其中插入了值。

现在,我需要仅购买(牛奶,黄油和Paneer)的客户列表。

All purchased items

2 个答案:

答案 0 :(得分:1)

确切购买了(牛奶,黄油和Paneer)的客户列表:

select cu.Customer_Name
 from Customer as cu inner join dbo.Product_Purchase as pu
 on pu.Customer_Id =cu.Customer_Id 
 where cu.Customer_Id not in 
 (select distinct pu.Customer_id  from  dbo.Product as pr inner join dbo.Product_Purchase as pu on pr.Product_Id=pu.Product_Id where Product_Name not in ('Milk', 'Butter','Paneer'))
 group by  cu.Customer_Name
 having count(pu.Product_id)=3 

答案 1 :(得分:0)

select customer_name
from Customer C, Product_Purchase PP, Product P
where C.Customer_Id = PP.Customer_Id
and   PP.Product_Id = P.Product_Id
and   Product_name in ('Milk', 'Butter', 'Paneer');