sql - Return only single record if name is test
问题描述
I have a 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')
My requirement is to return only 1 record for the id which is having 'Test' as name:
My output will return:
ID name
1 Test
2 R
2 S
3 T
I tried this query:
select * from @t t
where exists (select 1 from @t t1 where t.ID=t1.ID and name ='test')
But no luck.
Can anyone please tell me what is the issue here?
解决方案
你可以这样做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()
窗口功能:
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;
请参阅演示。
结果:
> ID | name
> -: | :---
> 1 | Test
> 2 | R
> 2 | S
> 3 | T
推荐阅读
- javascript - PUPPETER - 循环内的随机超时不起作用
- javascript - mongoose post.save 在heroku上失败,在本地主机上工作
- docker - 到 docker 容器的 IPv6 数据包似乎来自 docker 网络网关的 IPv4
- php - 我可以从 PHP 的 Interactive Shell 中的必需/包含文件中“使用”命名空间吗?
- android - React-native run-android 在插入的 android 4.1.2 手机上不起作用
- python - OCRmyPDF 错误:无法获取 http://security.ubuntu.com/
- go - Gin Go 框架中的测试
- c# - 基于从 MySQL 数据库更改 ID 的行颜色
- sql - 如何缩短 SQL 函数
- flutter - 在构建期间从父类 setState() 或 markNeedsBuild() 设置状态时