查找包含特定值的列的记录

时间:2013-03-28 16:37:21

标签: sql tsql select join

我认为我的问题实际上归结为对多个值执行sql IN

这是我到目前为止的SQL Fiddle

长话短说,我Cases有多个Types

我需要过滤包含特定Cases

Types

假设我有6行(col1,col2)......(1,2),(1,3)(1,4),(2,3),(2,4),(2,5) 如何仅选择在col2中具有2,AND 3 AND 4的Cases

2,3,4只是一个用例。它可能只是任何组合(SQL Fiddle有几个表决定了这一点)。

3 个答案:

答案 0 :(得分:0)

这有点接近吗?

SELECT * from CaseTypes CT
INNER JOIN TypeBillable TB    ON CT.TypeId = TB.TypeId
where CT.CaseId in
(
select CaseID from CaseTypes
PIVOT (count (TypeId) for TypeId in ([2],[3],[4])) as x
where [2] > 0 and [3] > 0 and [4] > 0
)

答案 1 :(得分:0)

尝试:

select [CaseId]
from CaseTypes
where [TypeID] in (2,3,4)
group by [CaseId]
having count(distinct [TypeID]) = 3

(SQLFiddle here

答案 2 :(得分:0)

你可能会尝试一些事情:

使用派生表:

SELECT a.col1
FROM (SELECT col1 FROM Cases WHERE col2 = 2) a
INNER JOIN (SELECT col1 FROM Cases WHERE col2 = 3) b ON a.col1 = b.col1
INNER JOIN (SELECT col1 FROM Cases WHERE col2 = 4) c ON a.col1 = c.col1

使用聚合:

SELECT col1
FROM Cases
GROUP BY col1
HAVING 
   SUM(CASE col2 WHEN 2 THEN 1 ELSE 0 END) > 0 AND
   SUM(CASE col2 WHEN 3 THEN 1 ELSE 0 END) > 0 AND
   SUM(CASE col2 WHEN 4 THEN 1 ELSE 0 END) > 0