所以我有一张像这样的桌子:
表1:
ID | metric1 | metric2
A | 1 | 1
A | 1 | 1
B | 2 | 3
C | 3 | 2
另一个可能具有项目备用ID的表格(请注意,新ID也将出现在上表中)。例如:
转化:
old_ID | new_ID
A | C
所以我正在尝试创建一个聚合新ID和旧ID的查询,但也保留旧ID(如果可用)。基本上我想要的结果看起来像这样:
ID | potential_old_ID | metric1 | metric2
C | A | 5 | 4
B | NULL | 2 | 3
到目前为止,根据我目前的策略,我已经能够接近这样的查询:
select
(CASE WHEN new_ID is null then ID else new_ID END) as ID,
(CASE WHEN new_ID is null then null else ID END) as potential_old_ID,
SUM(metric1),
SUM(metric2)
from table1
left join conversions on ID = old_ID
group by ID, new_ID
哪个让我接近,但它仍然在单独的行中分隔C和A,这对我的用例不起作用:
ID | potential_old_ID | metric1 | metric2
C | A | 2 | 2
B | NULL | 2 | 3
C | NULL | 3 | 2
如果我从组中删除new_ID,则会在查询中出现错误。无论如何,我可以得到我正在寻找的结果,我错过了吗?
答案 0 :(得分:1)
您需要确保具有C的行已经具有与A相同的潜在旧ID。例如
SELECT ID, potential_old_ID, SUM(metric1), SUM(metric2)
FROM
( select
(CASE WHEN c1.new_ID is null then ID else c1.new_ID END) as ID,
COALESCE(c1.old_ID, c2.old_ID) as potential_old_ID,
metric1,
metric2
from table1
left join conversions c1 on ID = c1.old_ID
left join conversions c2 on ID = c2.new_ID
) AS data
GROUP BY ID, potential_old_ID
答案 1 :(得分:0)
select coalesce(new_id, id) as id,
SUM(metric1),
SUM(metric2)
from table1 left join
conversions
on ID = old_ID
group by coalesce(new_id, id);