sql - TSQL 在 IN 运算符中获取丢失的记录
问题描述
我在 SQL Server 中有一个如下表:
create table address (id int, city varchar(10));
insert into address values (1, 'Rome');
insert into address values (2, 'Dallas');
insert into address values (3, 'Cracow');
insert into address values (4, 'Moscow');
insert into address values (5, 'Liverpool');
insert into address values (6, 'Cracow');
insert into address values (7, 'Seoul');
我正在用IN
运算符编写查询
SELECT City
FROM address
WHERE city IN ('Rome', 'Mumbai', 'Dallas', 'Delhi', 'Moscow')
我可以得到结果,但我想获取表中缺失或不可用记录的列表,例如
| City | Status |
+--------+-----------+
| Rome | Available |
| Dallas | Available |
| Moscow | Available |
| Mumbai | Missing |
| Delhi | Missing |
+--------+-----------+
解决方案
使用派生表 usingVALUES
用于所有有问题的城市,并使用CASE
表达式EXISTS
检查是否存在具有城市的地址。
SELECT city.name city,
CASE
WHEN EXISTS (SELECT *
FROM address
WHERE address.city = city.name) THEN
'Available'
ELSE
'Missing'
END status
FROM (VALUES ('Rome'),
('Mumbai'),
('Dallas'),
('Delhi'),
('Moscow')) city (name);
推荐阅读
- javascript - 谷歌表格脚本编辑器 - 保存后脚本不起作用
- python - 仅在修改后如何读取文本文件?
- android - Firebase 实时数据库密钥生成对于 Android/iOS 设备上的时钟变化是否可靠?#AskFirebase
- javascript - Vuelidate requiredIf 不使用复选框
- delphi - 如何自动增加内部版本号?
- asp.net-core - 在 RHEL 7 中运行 ASP.NET Core 的问题
- python - Pandas 列中的多个局部最大值超过阈值
- react-admin - 操作创建按钮路径
- visual-studio-2017-build-tools - 以正确的编码生成 .resx 资源文件
- docker - Docker 构建时间戳