选择在给定范围内具有子标的容器
我有两张表:
项目:
ID | 名称 |
---|---|
1 | ABC |
2 | DEF |
3 | GHI |
4 | JKL |
5 | MNO |
6 | PQR |
附件:
ID | 状态 | ProjectID |
---|---|---|
1 | A1 | 1 |
A1 | 1 | 2 |
3 | A2 | A1 1 |
A2 2 4 | A2 | 2 |
4 | 3 6 A2 | 3 |
7 | A2 2 5 A1 3 6 A2 | A1 |
4 | A1 | 4 |
8 A2 4 | A2 | 4 |
9 | A3 | 4 |
10 | A1 | 5 |
11 | A2 | 5 |
12 | A4 | 5 |
我想获得的项目名称,该项目名称只有具有状态A1和A2的作业(必须两个),并且不会在状态A3和A4中进行分配。 因此,结果应该是:
GHI
我尝试的是:
select distinct
p.Name
from
Attachment a
inner join Project p on p.Id = a.ProjectId
group by
p.Name, a.status
having (a.Status = 'a1' or a.Status = 'a2'
I have two tables:
Project:
Id | Name |
---|---|
1 | ABC |
2 | DEF |
3 | GHI |
4 | JKL |
5 | MNO |
6 | PQR |
Attachment:
Id | Status | ProjectId |
---|---|---|
1 | a1 | 1 |
2 | a1 | 1 |
3 | a2 | 2 |
4 | a2 | 2 |
5 | a1 | 3 |
6 | a2 | 3 |
7 | a1 | 4 |
8 | a2 | 4 |
9 | a3 | 4 |
10 | a1 | 5 |
11 | a2 | 5 |
12 | a4 | 5 |
I'd like to get projectnames which has assignments only with statuses a1 and a2 (must have both of them) and doesn't havve assignments in statuses a3 and a4.
So the result should be:
GHI
What I've tried wass:
select distinct
p.Name
from
Attachment a
inner join Project p on p.Id = a.ProjectId
group by
p.Name, a.status
having (a.Status = 'a1' or a.Status = 'a2'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
存在|不存在
关键字来实现这一目标。You can use
exist|not exists
keywords to achieve this.使用
String_agg
,subquery
和join
以获取所需的结果dbfiddle
use
String_agg
,Subquery
andjoin
to get your desired resultdbfiddle
您可以将计数与非在:
You can use count distinct in combination with NOT IN:
Here is a demo