【发布时间】:2020-01-18 17:33:03
【问题描述】:
这是我用来获取用户所属团队列表的查询:
select user_teams.team_id, teams.team_name from
(
select distinct(team_id) from workflows where workflow_id in (
select workflow_id from user_workflows where user_name in
(
'johndoe'
)
)
) user_teams join tbl_teams teams on user_teams.team_id = teams.team_id;
结果如下:
team_id team_name
1 Team A
5 Team E
如何添加另一列,其值是分配给用户的该团队的工作流数量?
(我可以从工作流和 user_workflows 表中找到它)
应该是这样的:
user_name team_id team_name workflow_count
johndoe 1 Team A 127
johndoe 5 Team E 96
我想出了这个查询,但我不知道如何根据之前的 team_id 和 user_name 将其结果添加到新列查询:
select count(distinct(workflow_id, user_name)) from user_workflows
where user_name = 'johndoe'
and workflow_id in
(
select workflow_id from workflows where team_id in
(
select team_id from tbl_teams where team_name in ('Team A')
)
)
关于如何实现这一点的任何提示?
编辑:
添加表定义:
tbl_teams(team_id bigserial, team_name text)
workflows(workflow_id bigserial, team_id int8 references(tbl_teams(team_id)), workflow_name)
user_workflows(user_workflow_id bigserial, workflow_id int8 references(workflows(workflow_id)), user_name text)
添加示例数据:
tbl_teams:
team_id team_name
1 Team A
2 Team B
3 Team C
4 Team D
5 Team E
workflows:
workflow_id team_id workflow_name
1 1 Audit
2 1 Refund
3 3 Purchase
4 4 Discontinue
5 3 Payment
user_workflows:
user_workflow_id workflow_id user_name
1 1 johndoe
2 1 janedoe
3 1 alex
4 3 ron
5 5 stacey
6 2 johndoe
7 2 janedoe
8 5 ron
9 5 johndoe
理想的查询结果:
user_name team_id team_name workflow_count
johndoe 1 Audit 2
johndoe 3 Payment 1
alex 1 Audit 1
ron 3 Purchase 2
【问题讨论】:
-
表定义对您有很大帮助。
-
试试这个:
with j as ( select user_teams.team_id, teams.team_name from ( select distinct(team_id) from workflows where workflow_id in ( select workflow_id from user_workflows where user_name in ('johndoe') ) ) user_teams join tbl_teams teams on user_teams.team_id = teams.team_id) select j.team_id, j.team_name, user_name, count(*) from j,user_workflows w where j.team_id = w.team_id group by j.team_id, j.team_name, w.user_name。考虑在您的问题中添加创建表语句和示例数据(插入语句).. -
@VBoka 我不确定这是 OP 所需要的,为了避免发布错误的答案并可能让其他人对回答这个问题失去兴趣,我更愿意先从 OP 获得反馈.
-
OP 描述了他的需求。如果你不明白,那么像 Bjarni 那样问你不明白的地方。此外,接受的答案不能阻止某些人参与,答案也不应该。例如,我们现在有了答案... :)
-
@BjarniRagnarsson 添加了表定义
标签: sql postgresql join