我正在运行
case when exists
以尝试从我的表中过滤掉 anamoly 数据,但我遇到了 unsupported correlated query
错误。
我有一个不同指标的异常表,如果这些指标值在这个异常表中,我想在我的最终结果中将它们清零。
我有一个表,
anomalytable
,它存储了一个 id,异常的度量类型,以及发生这种情况的日期范围。
| id | startdate | enddate | metrictype |
| ---- | --------- | ------- | -----------|
| 1 | 1/1/23 | 1/3/23 | metric1 |
| 2 | 1/3/23 | 1/5/23 | metric2 |
我有一个结果表,如果它们属于上表,我想在其中清空指标。
| id | metric1 | metric2 | date |
| ---- | --------- | ------- | -------|
| 1 | 300 | 1.2 | 1/2/23 |
| 2 | 1.1 | 500 | 1/4/23 |
我希望我的最终结果看起来像什么(如您所见,300 和 500 异常数字已被剔除)
| id | metric1 | metric2 | date |
| ---- | --------- | ------- | -------|
| 1 | null | 1.2 | 1/2/23 |
| 2 | 1.1 | null | 1/4/23 |
我的查询如下
select
case when exists
(select * from anomalytable b where a.id = b.id and a.date between b.startdate and b.enddate and b.metricname = metric1)
then null else a.metric1val end,
case when exists
(select * from anomalytable b where a.id = b.id and a.date between b.startdate and b.enddate and b.metricname = metric2)
then null else a.metric2val end
from resultstable a
但是每次我运行这个我都会得到
correlated subquery pattern not supported
错误。我已经通读了 redshift 不受支持的相关查询,但看不出我违反了什么规则。是否有可能以干净的方式用连接重写它?
改用左连接。更简单,可能更快。
select
r.id,
case when a.metricname = 'metric1' then null else r.metric1val end,
case when a.metricname = 'metric2' then null else r.metric2val end,
r.date
from resultstable r
left join anomalytable a on r.id = a.id and r.date between a.startdate and a.enddate
这是一个相关子查询,因为子查询的结果会根据在顶部查询中选择的行而变化。这最好通过连接来完成——更少的表扫描。
select a.id,
case when b.metrictype = 'metric1' then null
else metric1 end metric1,
case when b.metrictype = 'metric2' then null
else metric2 end metric2,
a."date"
from resultstable a
join anomalytable b
on a.id = b.id and a.date between b.startdate and b.enddate
;
这里有一个小提琴可以试试:http://sqlfiddle.com/#!17/e677c/6