gpt4 book ai didi

sql - 如何为下表编写 SQL 查询?

转载 作者:行者123 更新时间:2023-12-01 08:29:17 24 4
gpt4 key购买 nike

我的表是这样定义的:

名称也是字符串和属性。

ID | Name | Property

此表中的数据示例如下:

ID | Name | Property
1 Peter Newsletter
2 Paul Register
3 Peter Register
4 Shaun Newsletter
5 Steve Register

现在我想查询所有拥有特性通讯并注册的人。结果我应该得到彼得,因为他拥有这两种属性(property)。

所以结果表应该是这样的:

ID | Name | Property
1 Peter Newsletter
3 Peter Register

所以我试图查询的所有内容都是哪个人同时拥有特性通讯和注册。

最佳答案

这是一种方法:

select t.*
from table t
where exists (select 1
from table t2
where t2.name = t.name and t2.property = 'NewsLetter'
) and
exists (select 1
from table t2
where t2.name = t.name and t2.property = 'Register'
);

如果您只想要名称列表,也许使用 ids,我会这样做:

select t.name
from table t
where t2.property in ('NewsLetter', 'Register')
group by t.name
having count(distinct property) = 2;

如何获取 id 列表取决于您的数据库,例如 listagg()group_concat() string_agg().

关于sql - 如何为下表编写 SQL 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24262190/

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