SQL根据另一列的输入值列表列出一列的公共值?

时间:2012-10-23 18:52:32

标签: sql sql-server sql-server-2008

我们有一个带有SQL Server 2008后端的ASP.NET应用程序。 我们在SpecimenEvents表中进行了以下设置:

EventID SpecimenID  EventType
      1        101        A       
      2        102        A
      3        103        A
      4        101        B
      5        103        B
      6        101        C

给定一个SpecimenID列表作为输入 - 如何编写查询以仅返回那些EventType(s)COMMON到输入列表中的所有SpecimenID? 例如:

(101,102,103)的SpecimenID输入列表应返回'A'

(101)的SpecimenID输入列表应该返回'A','B','C'

一个(101,103)的SpecimenID输入列表应该返回'A','B'......

2 个答案:

答案 0 :(得分:2)

select distinct EventType
from (
    select EventType, count(distinct SpecimenID) as SpecimenCount
    from SpecimenEvents
    where SpecimenID in (101,103)
    group by EventType
    having count(distinct SpecimenID) = 2 -- Make this match the list length
) x

答案 1 :(得分:0)

试用此代码

    declare @1 varchar(10),@2 varchar(10), @3 varchar(10), @sql nvarchar(4000)
set @1='101'
set @2= '103'
set @3= null

set @sql =''
if @1 is not null set @sql = @sql+'
intersect
SELECT [EventType] from SpecimenEvents where [SpecimenID] = ' + @1
if @2 is not null set @sql = @sql+'
intersect
SELECT [EventType] from SpecimenEvents where [SpecimenID] = ' + @2
if @3 is not null set @sql = @sql+'
intersect
SELECT [EventType] from SpecimenEvents where [SpecimenID] = ' + @3
if len(@sql)>13 
begin
set @sql = substring(@sql,14,4000)
execute sp_executesql @sql
end

Amit Patel