Seb*_*ian 5 sql select join count
我正在寻找3个表的连接中的计数查询,这可以让我计算其中一个表的不同值.
我有3个表,我需要加入以获得预期的数据(Workflow,Message和Message_Workflow_Relation).
我想获得按Message结果(related_name)中状态+连接表的一个字段分组的工作流计数.相关名称应取自adapter字段等于的条目wf,但有时会有多个与此条件匹配的消息记录,这将导致我的计数中的数据集更多,然后是真正存在的数据集.
我很确定必须能够理清它,但是不要让它运转起来.遗憾的是,我无法更改表结构,因为它是我们使用的产品的给定模式.
我的表结构如下所示:
工作流程:
id | workflow_id | starttime | endtime | status
------------------------------------------------------
1 | 22 | 0 | 200 | OK
2 | 23 | 220 | 920 | ERROR
3 | 55 | 202 | 588 | OK
Run Code Online (Sandbox Code Playgroud)
Message_Workflow_Relation:
id | message_id | workflow_id |
-------------------------------
1 | 122 | 22 |
2 | 235 | 22 |
3 | 456 | 22 |
4 | 982 | 22 |
5 | 444 | 23 |
6 | 445 | 23 |
7 | 585 | 55 |
8 | 738 | 55 |
9 | 399 | 55 |
Run Code Online (Sandbox Code Playgroud)
信息:
id | message_id | starttime | endtime | adapter | related_name |
----------------------------------------------------------------
1 | 122 | 0 | 2335 | wf | workflow_1 |
2 | 235 | 222 | 1000 | other | other |
3 | 456 | 343 | 2330 | another | another |
4 | 982 | 222 | 2200 | wf | workflow_1 |
5 | 444 | 2223 | 3333 | wf | workflow_2 |
6 | 445 | 1123 | 1244 | manual | manual |
7 | 585 | 5555 | 5566 | wf | workflow_1 |
8 | 738 | 655 | 999 | wf | worfklow_1 |
9 | 399 | 6655 | 7732 | another | another |
Run Code Online (Sandbox Code Playgroud)
这应该返回以下结果:
count(*) | related_name | status |
----------------------------------
2 | workflow_1 | OK |
1 | workflow_2 | ERROR |
Run Code Online (Sandbox Code Playgroud)
我对以下声明感到困惑,但我不确定如何adapter = wf unique对每个工作流程进行选择:
select distinct
count(*),
m.related_name,
w.status
from
workflow as w,
message as m,
msg_bpm_rel as rel
where rel.workflow_id = w.workflow_id
and rel.message_id = m.message_id
and m.adapter = 'PE'
group by m.related_name,w.status
Run Code Online (Sandbox Code Playgroud)
这将返回我(4 workflow_1而不是2):
count(*) | related_name | status |
----------------------------------
4 | workflow_1 | OK |
1 | workflow_2 | ERROR |
Run Code Online (Sandbox Code Playgroud)
如何才能做出正确的查询来实现这一目标?
任何帮助赞赏.
您可以通过对不同的值进行分组和计数来实现。
所以像这样:
select count(distinct w.workflow_id), m.related_name,w.status
from workflow as w, message as m, msg_bpm_rel as rel
where rel.workflow_id = w.workflow_id and rel.message_id = m.message_id
and m.adapter = 'PE'
group by m.related_name, w.status
Run Code Online (Sandbox Code Playgroud)
这未经测试,但我认为应该可以工作:)
| 归档时间: |
|
| 查看次数: |
35641 次 |
| 最近记录: |