【发布时间】:2022-11-30 18:18:37
【问题描述】:
我有一个 POST 表、一个 CATEGORY 表、一个 ACTION 表和 ACTION_TYPE 表,我解释说 ACTION 表包含所有已执行的操作,而表 ACTION_TYPE 包含操作详细信息,例如 ID = 4 的 ACTION 具有 ACTION_TYPE_ID = 1对于 POST_ID 6,这意味着对 50 号帖子进行了操作,我们可以对一个 post_id 执行多个操作
POST 表
id title content category_id
---------- ---------- ---------- ------------
1 title1 Text... 1
2 title2 Text... 1
3 title3 Text... 1
4 title4 Text... 3
5 title5 Text... 2
6 title6 Text... 1
类别表
id name
---------- ----------
1 category_1
2 category_2
3 category_3
ACTION_TYPE 表
id name
---------- ----------
1 updated
2 deleted
3 restored
4 hided
行动表
id post_id action_type_id date
---------- ---------- -------------- -----
1 1 1 2017-01-01
2 1 1 2017-02-15
3 1 3 2018-06-10
4 6 1 2019-08-01
5 5 2 2019-12-09
6 2 3 2020-04-27
7 2 1 2020-07-29
8 3 2 2021-03-13
现在我解释一下这个案例,我实际上有两个查询,一个查询计算每个类别的帖子,另一个查询按类别计算对每个帖子执行的操作,这非常有效。
这是我的第一个查询
select categories, count(*) as cnt_posts_per_cat
from(
select
case
when p.category_id is not null then c.name
end as categories
from post p
left join category c on p.category _id = c.id
)
group by categories
;
这带来了这个结果
categories cnt_posts_per_cat
---------- -------------------
category_1 4
category_2 1
category_3 1
Ans 这是我的第二个查询
select categories, count(*) as cnt_actions_per_cat
from(
select distinct ac.post_id AS action_post_id, max(ac.date) over (partition by ac.post_id) as max_date,
case
when ac.action_type_id is not null then act.name
end as actions,
case
when p.category_id is not null then c.name
else 'na'
end as categories
from action ac
left join post p on ac.post_id = p.id
left join category c on p.category _id = c.id
left join action_type act on ac.action_type_id = act.id
where act.name in ('restored','deleted','updated')
)
group by categories
;
这带来了这个正确的结果,因为它选择了每个 action_type 的最后一个动作
categories cnt_actions_per_cat
---------- -------------------
category_1 3
category_2 1
category_3 na
但我想同时为两个查询创建一个结果表,如下所示: 这是预期的结果
categories cnt_posts_per_cat cnt_actions_per_cat
---------- ----------------- -------------------
category_1 4 3
category_2 1 1
category_3 1 na
我正在尝试 union 和 union all 但它不正确它返回以下结果
categories cnt_posts_per_cat
---------- -----------------
category_1 7
category_2 2
category_3 1
此致
【问题讨论】:
标签: oracle oracle11g oracle-sqldeveloper