Return 如果名称为 test,则只有一条记录

Return only single record if name is test

我有一个 table:

Declare @t table (ID int,name nvarchar(100))

Insert into @t values (1,'Test')
Insert into @t values (1,'A')
Insert into @t values (1,'B')
Insert into @t values (2,'R')
Insert into @t values (2,'S')
Insert into @t values (3,'T')

我的要求是 return 只有 1 条以 'Test' 作为名称的 ID 的记录:

我的输出将 return:

ID  name
1   Test    
2   R   
2   S   
3   T   

我试过这个查询:

select * from @t t
where exists (select 1 from @t t1 where t.ID=t1.ID and name ='test') 

但运气不好。

谁能告诉我这是什么问题?

你可以用 NOT EXISTS:

SELECT t.*
FROM @t t
WHERE t.name = 'Test'
OR NOT EXISTS (SELECT 1 FROM @t WHERE ID = t.ID AND name = 'Test')

或者用MAX()window函数:

SELECT ID, name
FROM (
  SELECT *, 
    MAX(CASE WHEN name = 'Test' THEN name END) OVER (PARTITION BY ID) test
  FROM @t
) t
WHERE test IS NULL OR name = test;

参见demo
结果:

> ID | name
> -: | :---
>  1 | Test
>  2 | R   
>  2 | S   
>  3 | T  

您可以按如下方式使用DENSE_RANK

select id,name from 
(select id, name, 
        DENSE_RANK()
          over(partition by id 
               order by case when t.id = 1 then 1 else 2 end) rn
from @t)t
where t.rn = 1