sql - 仅选择具有 COLUMN= 的行如果匹配存在,否则 COLUMN IS NULL
问题描述
这是一个示例脚本来演示该问题:
CREATE TABLE person (
id NUMERIC PRIMARY KEY,
name VARCHAR(255) NOT NULL,
city VARCHAR(255)
);
INSERT INTO person(id, name, city) VALUES(1, 'John', 'New York');
INSERT INTO person(id, name, city) VALUES(2, 'Mike', 'Boston');
INSERT INTO person(id, name, city) VALUES(3, 'Ralph', NULL);
因为city='Boston'
我只想返回第二行。因为city='Chicago'
我希望返回第三行。
解决方案
如果您正在寻找一排:
select p.*
from person p
where city is null or city = 'Boston'
order by (city = 'value') desc
fetch first 1 row only;
如果您可以有多个匹配项,那么我建议:
select p.*
from person p
where p.city = 'Boston'
union all
select p.*
from person p
where p.city is null and
not exists (select 1 from person p2 where p2.city = 'Boston');
或者,使用窗口函数:
select p.*
from (select p.*, count(*) filter (where p.city = 'Boston') as cnt
from person p
) p
where (cnt > 0 and p.city = 'Boston') or
(cnt = 0 and p.city is null);
推荐阅读
- python - 将 send_keys 限制为特定数量的字符
- spotfire - 如何取消合并 Spotfire 交叉表中的行
- php - 如何将 postfix 配置为可以登录的 SMTP 服务器?
- android - 设置任务描述时android应用程序崩溃
- python - BeautifulSoup.get_text() 忽略换行符
- python-3.7 - 在 python 3.7.4 0 中使用附加模式创建的文件
- java - 声明一个继承自 Employee 类的 Manager 类 (Java)
- python - Pyspark Grouped Map Pandas UDF - 它是否保持组中行的顺序?
- java - 我得到了我在 networkstatsmanager.querydetailsforuid() 方法中提供的不同的 startTimestamp 和 endtimestamp。如何解决?
- spring - Hibernate 不添加 auto_increment