仅使用一种类型的代码检索ID

时间:2019-01-28 13:23:42

标签: sql sql-server

表格示例

ID     Code
2324    1
2324    2
2325    1
2326    1
2326    2

我想获取仅包含代码“ 1”而不包含代码“ 2”的ID,因此结果应为

2325    1

由于其他人的代码分别为1和2

我尝试过

SELECT * FROM TABLE
WHERE CODE != 1 AND CODE = 2

但是无论ID是否也具有代码1,这只会返回ID为2的任何ID

5 个答案:

答案 0 :(得分:6)

select ID, min(code) from t1
group by ID 
having min(code) = 1 and max(code) = 1

答案 1 :(得分:4)

不存在:

SELECT * FROM TABLE T
WHERE T.Code = 1 AND NOT EXISTS (
  SELECT 1 FROM TABLE WHERE ID = T.ID AND Code <> T.Code
)

答案 2 :(得分:2)

尝试一下:

select * from myTable t1
where not exists(select 1 from myTable
                 where t1.id = id and Code <> 1)

答案 3 :(得分:0)

不存在

select * from table t1 where Not exists 
( select 1 from table t2 where t1.id=t2.id and
  t2.code=2)

with cte as
(
select 2324 as id ,1 as code union all
select 2324 ,2
union all
select 2325,1
union all
select 2326,1 union all
select 2326 ,2
)
select * from cte t1 where Not exists 
( select 1 from cte t2 where t1.id=t2.id and
  t2.code=2)

demo link

 id     code
 2325    1

答案 4 :(得分:0)

您可以尝试一下。

SELECT * FROM TABLE 
WHERE T.Code = 1 AND NOT EXISTS (
  SELECT 1 FROM TABLE WHERE ID = T.ID AND Code <> T.Code
)