检索两个字段值都存在于同一表中的记录

时间:2019-06-14 12:51:07

标签: sql join union common-table-expression

我有表'ReceiverDet'和列名'ReceiverNo'和'PartNo'。我想检索“ PartNo”等于“ CoC”和用户输入值(即“ 44661”)的所有记录。然后,我只想检索包含两个“ PartNo”值和相同“ ReceiverNo”的记录。

我已经尝试了UNION,JOIN和CTE,但是我什至不能确定CTE是答案。

ReceiverDet表

+------------+--------+
| ReceiverNo | PartNo |
+------------+--------+
| 1001       | 9173   |
+------------+--------+
| 1002       | CoC    |
+------------+--------+
| 1003       | 5432   |
+------------+--------+
| 1003       | CoC    |
+------------+--------+
| 1002       | 44661  |
+------------+--------+

在此示例中,我希望最终结果为ReceiverNo“ 1002”,因为它同时包含“ CoC”和用户输入的值“ 44661”。

1 个答案:

答案 0 :(得分:1)

如果ReceiverNoPartNo是表上的组合键(唯一标识一条记录),则可以执行以下操作:

SELECT
  ReceiverNo
FROM
  ReceiverDet
WHERE
  PartNo = 'CoC'
  OR
  PartNo = @UserInput
GROUP BY
  ReceiverNo
HAVING
  COUNT(DISTINCT PartNo) = 2;