需要SQL只提供计算机和卡车的供应商名称列表

时间:2015-06-03 10:44:54

标签: sql sql-server

我有一个表名为Test的两列,即:“Supplier Name”和“Product Name”。现在,我希望供应商名称仅在'卡车'和'计算机'中处理。如下所示,该查询的结果应仅返回“Ajit”。 虽然Gaurav还经营'卡车'和'计算机',但他也处理'BC',所以查询结果应该只返回供应商名称为Ajit!

测试:

**SuppliarName**        **Product Name**
Gaurav              Truck
Ajit                Computer
Rahul               Jhadu
Gaurav              Computer
Gaurav              BC
Ajit                Truck

2 个答案:

答案 0 :(得分:1)

SELECT * FROM dbo.Table1 t1
WHERE EXISTS (SELECT * FROM dbo.Table1 t2 
                WHERE t1.SuppliarName = t2.SuppliarName 
                AND t2.[Product Name] = 'Computer')
 AND EXISTS (SELECT * FROM dbo.Table1 t3 
                WHERE t1.SuppliarName = t3.SuppliarName 
                AND t3.[Product Name] = 'Truck')
 AND NOT EXISTS (SELECT * FROM dbo.Table1 t4 
                WHERE t1.SuppliarName = t4.SuppliarName 
                AND t4.[Product Name] NOT IN ('Computer', 'Truck'))

http://sqlfiddle.com/#!6/fc6f9/1

答案 1 :(得分:1)

在OP表明他的努力之前,我没有回答这个问题,但jarlh关于自我加入而不是存在的评论说服我说明单独使用其中任何一个选项是可能的:

自我左联:

SELECT DISTINCT t1.SuppliarName
FROM Tbl t1
LEFT JOIN Tbl t2 ON(t1.SuppliarName = t2.SuppliarName 
                    AND t2.ProductName NOT IN('Truck', 'Computer'))
WHERE t1.ProductName IN('Truck', 'Computer')
AND t2.SuppliarName IS NULL;

不存在:

SELECT DISTINCT t1.SuppliarName
FROM Tbl t1
WHERE t1.ProductName IN('Truck', 'Computer')
AND NOT EXISTS(
  SELECT 1
  FROM Tbl t2
  WHERE t1.SuppliarName = t2.SuppliarName 
  AND t2.ProductName NOT IN('Truck', 'Computer')
)

see fiddle here.

更新我可能误解了这个问题。如果要求供应商出售计算机和卡车,那么三重自我加入或不存在的自我加入就可以解决问题:

三重自我加入:

    SELECT DISTINCT t1.SuppliarName
FROM Tbl t1
INNER JOIN Tbl t2 ON(t1.SuppliarName = t2.SuppliarName 
                     AND t1.ProductName <> t2.ProductName) 
LEFT JOIN Tbl t3 ON(t1.SuppliarName = t3.SuppliarName 
                    AND t3.ProductName NOT IN('Truck', 'Computer'))
WHERE t1.ProductName ='Truck'
AND t2.ProductName = 'Computer'
AND t3.SuppliarName IS NULL;

自我加入并不存在:

SELECT DISTINCT t1.SuppliarName
FROM Tbl t1
INNER JOIN Tbl t2 ON(t1.SuppliarName = t2.SuppliarName 
                     AND t1.ProductName <> t2.ProductName) 
WHERE t1.ProductName ='Truck'
AND t2.ProductName = 'Computer'
AND NOT EXISTS (
    SELECT 1
    FROM tbl t3 
    WHERE t3.SuppliarName = t1.SuppliarName
    AND t3.ProductName NOT IN('Truck', 'Computer')
)

see fiddle here.