postgresql 存在时不支持的关联查询红移

7bsow1i6  于 2023-04-29  发布在  PostgreSQL
关注(0)|答案(2)|浏览(144)

我正在运行case when exists,试图从我的表中过滤掉异常数据,但我遇到了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.metric1 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.metric2 end
from resultstable a

但是每次我运行它,我都会得到correlated subquery pattern not supported错误。我已经通读了redshift不支持的相关查询,看不出我违反了什么规则。有没有可能用一种干净的方式重写这个连接?

ajsxfq5m

ajsxfq5m1#

请改用左联接。更简单,可能更快。

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
c86crjj0

c86crjj02#

这是一个相关子查询,因为子查询的结果会根据顶部查询中选定的行进行更改。使用join可以更好地完成这一点--减少表扫描。

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

相关问题