需要sql查询在一个查询中从同一个表中提取满足多组条件的数据

时间:2016-10-02 14:55:11

标签: sql sql-server

我需要编写一个sql查询,它将从同一个表中提取满足几组条件的数据。最简单的描述方式是想象使用SQL""条款,但不是该条款的内部是"或者加入你希望它匹配的参数而是"和"。

我尝试使用计数来验证每个""中的数据被拉回的数据是否正确。声明,但由于每列的其他条目相似,因此无法始终信任该计数。

示例表可能是这样的:

id   count  animal
---  -----  ------
1      5    puppy
1      6    cat
1      6    puppy

所以,现在我需要一个查询,它将返回id为1且计数为5和6的所有条目以及一只小狗和猫的动物。我非常需要验证表条目的整个路径,以便知道我想将其拉回来。是否有内置功能可以做到这一点?在确认满足一组标准后,是否需要使用递归CTE深挖?谢谢你的帮助。

3 个答案:

答案 0 :(得分:1)

如果我做对了

with cnt as(
    select id
    from tbl
    where [count] in (5,6) and animal in ('puppy', 'cat')
    group by id
    having count(distinct[count])=2 and count(distinct animal)=2
)
select id, [count], animal
from tbl 
where id in (select id from cnt);

答案 1 :(得分:0)

我想你只是想:

select t.*
from t
where id = 1 and
      count in (5, 6) and
      animal in ('puppy', 'cat');

编辑:

如果您希望它们全部在同一行,只需重新排列条件:

select t.*
from t
where id = 1 and
      ( (count = 5 and animal = 'puppy') or
        (count = 6 and animal = 'cat')
      );

答案 2 :(得分:0)

令人困惑的是你正在寻找什么,但是你不能使用或者和吗?

select id, count, animal 
from table 
where id = 1 and
      (count = 5 or count = 6) and
      (animal = puppy or anmial = cat)