sql查询带回多个结果

时间:2014-06-24 16:59:06

标签: sql

我有一个包含以下列的数据库表

 Id    ReviewStreamTypeId    ReviewerTitleTypeId     ReviewStreamReviewerOrderNumber
 1             1                      1                           1
 2             1                      27                          2
 3             1                      9                           3
 4             2                      1                           1
 5             2                      27                          2 
 6             2                      10                          3
 7             3                      1                           1
 8             3                      16                          2
 9             3                      24                          3

我正在尝试编写一个查询,获取所有ReviewStreamTypeId,其中ReviewerTitleTypeId = 1,ReviewStreamReviewerOrderNumber = 1,ReviewerTitleTypeId = 27,ReviewStreamReviewerOrderNumber = 2.所以我正在寻找结果集1,2

这是我写的查询,但不起作用

 select ReviewStreamTypeId 
 from Routing.ReviewStreamReviewerOrder 
 where (ReviewerTitleTypeId = 1 and ReviewStreamReviewerOrderNumber = 1) 
 and (ReviewerTitleTypeId = 27 and ReviewStreamReviewerOrderNumber = 2 )

有关如何编写查询以恢复正确结果的任何想法?

1 个答案:

答案 0 :(得分:4)

您想使用聚合和having子句:

 select ReviewStreamTypeId 
 from Routing.ReviewStreamReviewerOrder 
 group by ReviewStreamTypeId
 having sum(case when ReviewerTitleTypeId = 1 and ReviewStreamReviewerOrderNumber = 1 then 1 else 0 end) > 0 and
        sum(case when ReviewerTitleTypeId = 27 and ReviewStreamReviewerOrderNumber = 2 then 1 else 0 end) > 0;