我正在尝试编写一个查询,以查找最新的项目。该查询来自两个表:
Service_Item - Holds information on items such as Jira tickets / epics / sprints
id
item_type
Service_Item_Links - Many to Many table for service items. This ticket is part of this epic, ect.
link_type
parent_service_item (fk to service_items)
child_service_item (fk to service_items)
action_key ('added' or 'removed')
给定一组parent_service_items,找到相关的子服务项并返回它们的列表。为了仅查找直接子代,我使用查询来简单查找所有关联子代。然后,我在递归的postgres函数中使用此查询,直到没有子项为止。
select child_service_item_id, action_date
from service_item_links
where parent_service_item_id = ANY(source_ids)
and link_type = ANY(link_types)
and company_id=cid;
我的目标是更新此文件,以处理最后一个项目被删除的情况。以这种情况为例。
epic 1
ticket 1
links (added, removed)
ticket 2
links (added)
epic 2
ticket 1
links (added)
ticket 2
links (added)
如果给定史诗1作为父ID,则仅应返回票证2。如果将史诗1和史诗2作为父母ID,则应返回票证1和票证2。上面的查询当前为史诗1提供票证1和票证2。
您可以通过jira想象到,这些示例变得更加复杂。关于如何最好地对此进行过滤的任何想法,以便仅在添加了最新操作的情况下才包括故障单。该表包含一个action_key和一个时间戳,该action_key是一个字符串“ added”或“ removed”。
谢谢。
样本数据:
service_items
ID | 物品种类 |
---|---|
1个 | 史诗 |
2 | 史诗 |
3 | 卡 |
4 | 卡 |
service_item_links
link_type | parent_service_item | child_service_item | 动作日期 | 动作键 |
---|---|---|---|---|
“ has_child” | 1个 | 3 | '2020-01-01 00:00:00' | '添加' |
“ has_child” | 1个 | 3 | '2020-01-02 00:00:00' | “已删除” |
“ has_child” | 1个 | 3 | '2020-01-03 00:00:00' | '添加' |
“ has_child” | 1个 | 4 | '2020-01-01 00:00:00' | '添加 |
“ has_child” | 2 | 3 | '2020-01-01 00:00:00' | '添加' |
“ has_child” | 2 | 4 | '2020-01-01 00:00:00' | '添加' |
是以上示例的示例数据。
给定父ID为1,应返回子ID为4。
给定父级ID {1,2},则应返回子级3和4。
如果删除的行无法再添加,则可以通过以下方法实现:
SELECT DISTINCT
t.child_service_item, action_date
FROM
service_item_links t
WHERE
t.parent_service_item IN (1, 2)
AND NOT EXISTS
(
SELECT
1
FROM
service_item_links t2
WHERE
t2.parent_service_item = t.parent_service_item
AND t2.child_service_item = t.child_service_item
AND t.action_key = 'removed'
);
如果以后可以再次添加该行,则需要找出该行的最后一个action_type:
;WITH cte AS (
SELECT *, FIRST_VALUE(action_key) OVER (PARTITION BY parent_service_item, child_service_item ORDER BY action_date DESC) last_action_type
FROM service_item_links
)
SELECT parent_service_item, child_service_item, MAX(action_date) AS action_date
FROM cte
WHERE last_action_type ='added'
AND parent_service_item IN (1, 2)
GROUP BY cte.parent_service_item, child_service_item
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句