我们的营销团队会跟踪他们所谓的“关键”帐户的活动。数据每个星期一更新,上周的数据存档到“快照”表中。结构很简单
'AccountID','ContactID','Tag','Last Modified Date'
'602','31262001','Key','2018-08-07 22:43:57'
'608','91285974','Key','2018-08-07 22:43:55'
'608','28620737','Key','2018-08-07 22:43:57'
'4002','118697713','Key','2018-09-08 06:46:49'
'9481','112536097','Key','2018-08-07 22:43:56'
每个星期一,我必须报告
对于1)和2),我做到了
SELECT t1.*
FROM current_week t1
LEFT OUTER JOIN snapshot t2 ON t1.AccountID = t2.AccountID AND t1.ContactID
= t2.ContactID
WHERE t2.Tag = 'Key'
UNION
SELECT t2.*
FROM current_week t1
RIGHT OUTER JOIN snapshot t2 ON t1.AccountID = t2.AccountID AND t1.ContactID
= t2.ContactID
WHERE t2.Tag = 'Key';
注意:出于某种原因,市场营销允许帐户使用1:M ContactID值,这似乎在我的数据中产生了误报。出于这个原因,我添加了联接。
但是我不确定该怎么做3)。有想法吗?
答案 0 :(得分:1)
我认为您只能使用一个UNION ALL
来完成此操作。
第一个查询将添加快照中缺少的“关键”标签,并获取那些不是“关键”标签的标签。
然后让第二个查询只添加仅在快照中的那些。
SELECT curr.*
FROM current_week AS curr
LEFT JOIN snapshot AS prev ON (prev.AccountID = curr.AccountID AND prev.ContactID = curr.ContactID)
WHERE (curr.Tag != 'Key' OR (curr.Tag = 'Key' AND prev.Tag is null))
UNION ALL
SELECT prev.*
FROM snapshot AS prev
LEFT JOIN current_week AS curr ON (curr.AccountID = prev.AccountID AND curr.ContactID = prev.ContactID)
WHERE curr.Tag is null
ORDER BY AccountID;
您可以在 db <>小提琴here
上对其进行测试