gpt4 book ai didi

sql - 如何选择与列表中所有值匹配的值?

转载 作者:行者123 更新时间:2023-11-29 14:13:32 25 4
gpt4 key购买 nike

我正在尝试为同一列上的 2 个条件获取两个单独的行值。

例如这个数据:

id       status
----------------
1 0
1 2
1 3
2 2
2 0

我想选择 status = 0status = 2 的所有行。

所以例如输出应该是:

id       status
----------------
1 0
1 2
2 0
2 2

谢谢!

最佳答案

一种方法是:

where status in (0, 2)

但我怀疑您想要id两个 值。在这种情况下,一种方法使用 exists:

select t.*
from t
where status in (0, 2) and
exists (select 1
from t t2
where t2.id = t.id and
t2.status in (0, 2) and
t2.status <> t.status
);

如果您只需要 id,那么聚合很容易:

select id
from t
where status in (0, 2)
group by id
having count(*) = 2;

这可以合并到查询中以使用 inexistsjoin 获取原始行。或者窗口函数:

select t.*
from (select t.*,
count(*) filter (where status in (0, 2)) over (partition by id) as cnt
from t
) t
where cnt = 2;

关于sql - 如何选择与列表中所有值匹配的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57143910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com