2

I'm trying to read tutorials and find question on syntax on sql subqueries for a specific purpose but I can't seem to find the right choice of words to describe my problem.

Table - Part Descriptions

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

I basically need to find any part number that has the Type Value of both '2' and '4', not one or the other.

I feel like it should be incredibly simple, but I can't seem to get correct results

4

4 回答 4

9

您可以使用 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

如果您只想返回仅输入 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

演示

于 2013-10-09T20:24:19.510 回答
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)
于 2013-10-09T20:25:36.533 回答
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
    )
  )
于 2013-10-09T20:29:33.650 回答
0

这会起作用:

SELECT PartNumber, COUNT(*)
FROM Table
WHERE Type IN (2, 4)
GROUP BY PartNumber HAVING COUNT(*) > 1
于 2013-10-09T20:24:13.453 回答