Sql - 如何搜索具有两个特定变量的不同行

时间:2013-10-09 20:21:14

标签: sql sql-server

我正在尝试阅读教程并在sql子查询上找到有关特定目的的语法问题,但我似乎找不到合适的词语来描述我的问题。

表格 - 部分描述

+------------+------------+------------+
| ID         | Part #     |    Type    |
+------------+------------+------------+
| 1          |     123    |      1     |
| 2          |     456    |      2     |
| 3          |     123    |      3     |
| 4          |     789    |      4     |
| 5          |     123    |      4     |
| 6          |     789    |      2     |
| 7          |     123    |      2     |
+------------+------------+------------+

我基本上需要找到类型值为“2”和“4”的任何部件号,而不是其中之一。

我觉得它应该非常简单,但我似乎无法得到正确的结果

4 个答案:

答案 0 :(得分:8)

您可以使用WHERE,GROUP BY和HAVING子句的组合来获取结果。 HAVING子句中的关键是计算WHERE过滤器中包含的不同项:

select [part #]
from partDescriptions
where type in (2, 4)
group by [part #]
having count(distinct type) = 2;

请参阅SQL Fiddle with Demo

如果你只想返回只有2和4类型的部分,那么你可以扩展一下:

select PartNum
from yourtable
where type in (2, 4)
  and partnum not in (select partnum
                      from yourtable 
                      where type not in (2, 4))
group by PartNum
having count(distinct type) = 2

请参阅Demo

答案 1 :(得分:1)

SELECT *
FROM PartDesciption P
WHERE EXISTS (SELECT * FROM PartDesciption WHERE ID = P.ID AND Type = 2) AND
      EXISTS (SELECT * FROM PartDesciption WHERE ID = P.ID AND Type = 4)

答案 2 :(得分:0)

这样可行:

SELECT PartNumber, COUNT(*)
FROM Table
WHERE Type IN (2, 4)
GROUP BY PartNumber HAVING COUNT(*) > 1

答案 3 :(得分:0)

您希望零件号缺少两个必需值。以下查询似乎很复杂,但它比这类问题的一些更简单的解决方案更容易推广到类似的要求。

如果您有一个列出所有有效部件号的表,您可以在最外面的SELECT中使用它以避免需要SELECT DISTINCT。

WITH RequiredParts(p) AS (
  SELECT 2 UNION ALL SELECT 4
)
  SELECT DISTINCT([Part #]) AS [Part #]
  FROM [Part Descriptions] AS PD
  WHERE NOT EXISTS (
    SELECT * FROM RequiredParts AS RP
    WHERE NOT EXISTS (
      SELECT * FROM [Part Descriptions] AS PD2
      WHERE PD2.[Part #] = PD.[Part #]
      AND PD2.[Type] = RP.p
    )
  )