销售表包括从表中的“经销商ID”列表示的经销商处购买汽车的客户的客户ID的详细信息。 vin列是客户购买的汽车的ID。
发牌人表包括发牌人的ID和发牌人的名称。发牌人表中的发牌人ID与销售表中的发牌人ID的详细信息相同。
客户表包含客户的ID和客户的名称。客户表中的客户ID在销售表的客户ID列中具有相同的详细信息。
答案 0 :(得分:1)
正如评论所表明的,这个问题应该有所改善。因此,下面是使用数据创建表的代码。
IF OBJECT_ID('dbo.sale', 'U') IS NOT NULL
DROP TABLE dbo.sale;
IF OBJECT_ID('dbo.customer', 'U') IS NOT NULL
DROP TABLE dbo.customer;
IF OBJECT_ID('dbo.dealer', 'U') IS NOT NULL
DROP TABLE dbo.dealer;
CREATE TABLE sale(
SI_no VARCHAR(5),
vin VARCHAR(5),
customer_id VARCHAR(5),
dealer_id VARCHAR(5));
CREATE TABLE customer (
customer_id VARCHAR(5),
cust_name VARCHAR(10));
CREATE TABLE dealer (
dealer_id VARCHAR(5),
dealer_name VARCHAR(10));
INSERT INTO sale (SI_no,vin,customer_id,dealer_id) VALUES ('01','1v','1c','2d')
INSERT INTO sale (SI_no,vin,customer_id,dealer_id) VALUES ('02','2v','2c','4d')
INSERT INTO sale (SI_no,vin,customer_id,dealer_id) VALUES ('03','3v','1c','4d')
INSERT INTO sale (SI_no,vin,customer_id,dealer_id) VALUES ('04','4v','2c','3d')
INSERT INTO sale (SI_no,vin,customer_id,dealer_id) VALUES ('05','1v','1c','2d')
INSERT INTO sale (SI_no,vin,customer_id,dealer_id) VALUES ('06','2v','1c','4d')
INSERT INTO sale (SI_no,vin,customer_id,dealer_id) VALUES ('07','3v','1c','3d')
INSERT INTO sale (SI_no,vin,customer_id,dealer_id) VALUES ('08','4v','1c','3d')
INSERT INTO sale (SI_no,vin,customer_id,dealer_id) VALUES ('09','1v','2c','3d')
INSERT INTO sale (SI_no,vin,customer_id,dealer_id) VALUES ('10','3v','1c','1d')
INSERT INTO sale (SI_no,vin,customer_id,dealer_id) VALUES ('11','4v','1c','1d');
INSERT INTO customer (customer_id,cust_name) VALUES ('1c','hari')
INSERT INTO customer (customer_id,cust_name) VALUES ('2c','sam');
INSERT INTO dealer (dealer_id,dealer_name) VALUES ('1d','Honda')
INSERT INTO dealer (dealer_id,dealer_name) VALUES ('2d','Toyota')
INSERT INTO dealer (dealer_id,dealer_name) VALUES ('3d','Hyundai')
INSERT INTO dealer (dealer_id,dealer_name) VALUES ('4d','Ferrari');
您的问题的答案是将表作为您的列名称以及客户购买的值转向不同的经销商。然后,您执行联接以带来所需的信息。您应该执行WHERE
子句。
SELECT A.[customer_id],c.[cust_name]
FROM (
SELECT [customer_id],
SUM(CASE WHEN [dealer_id] = '1d' THEN 1 ELSE 0 END) AS Honda,
SUM(CASE WHEN [dealer_id] = '2d' THEN 1 ELSE 0 END) AS Toyota,
SUM(CASE WHEN [dealer_id] = '3d' THEN 1 ELSE 0 END) AS Hyundai,
SUM(CASE WHEN [dealer_id] = '4d' THEN 1 ELSE 0 END) AS Ferrari
FROM [sale]
GROUP BY [customer_id])A
JOIN [customer] AS c
ON A.[customer_id]=c.[customer_id]
WHERE A.Honda>0 AND A.Toyota>0 AND A.Hyundai>0 AND A.Ferrari>0