我有一个有几个重复条目的行的表。
|[com_enq_id]| [comtype_type] |
| 1 | blah |
| 1 | Found DP Quotes |
| 1 | Found Quotes |
| 2 | Found DP Quotes |
| 2 | blah |
| 2 | Found DP Quotes |
| 3 | Found DP Quotes |
| 3 | Found DP Quotes |
| 3 | Found DP Quotes |我试图只从表中选择[com_enq_id]没有Found DP Quotes和Found Quotes的行。应该选择具有其中一个或任何一个的ID,但不应该选择两者兼具的ID。(例如,在这种情况下,只应选择2和3 )
我尝试了我最初认为正在工作的以下内容,但如果该ID与另一个[comtype_type] (例如,blah)有任何额外的行,它也会返回包含这两个行的任何行:
SELECT
t1.[com_enq_id]
,t1.[comtype_type], t2.[comtype_type]
FROM [comments_view] t1
JOIN [comments_view] t2
ON t1.[com_enq_id] = t2.[com_enq_id]
WHERE
( t1.[comtype_type] = 'Found Quotes' AND t2.[comtype_type] <> 'Found DP Quotes')
OR
( t2.[comtype_type] = 'Found Quotes' AND t1.[comtype_type] <> 'Found DP Quotes')有人能指出我需要如何修改它以排除那些行/只选择没有两者的[com_enq_id]s吗?
发布于 2015-03-11 12:18:48
我认为处理这类问题的最简单和最灵活的方法是使用group by和having。获取com_enq_id的列表
select cv.com_enq_id
from comments_view cv
where comtype_type in ('Found DP Quotes', 'Found Quotes')
group by cv.com_enq_id
having count(distinct comtype_type) <> 2;然后,您可以以各种方式获取所有行。这使用in
select cv.*
from comments_view cv
where cv.com_enq_id in (select cv.com_enq_id
from comments_view cv
where comtype_type in ('Found DP Quotes', 'Found Quotes')
group by cv.com_enq_id
having count(distinct comtype_type) <> 2
);https://stackoverflow.com/questions/28986363
复制相似问题