查询中的Heroku dataclip变量替换

时间:2018-01-08 08:46:49

标签: postgresql heroku heroku-postgres

我想在查询的顶部设置一些参数/变量,并在Heroku Dataclips上的复杂查询中的几个位置使用它们。 这是一个简单的例子:

WITH vars AS ( SELECT 
  '2018-01-07' AS calcdate,
  12345 AS salary
)
select * 
from taxes
where country_alpha3='USA' and year='2018' and active=true 
and subdivision_code='US-MEDI' 
and local_code is null
and start_date <= DATE(vars.calcdate) and end_date >= DATE(vars.calcdate) 
and lower_amount_cents <= vars.salary and upper_amount_cents >= vars.salary;

我在另一个答案(从2013年)中看到了这种代码风格,并且它在今天的实际dataclip中无效。

Error: Your query couldn't be updated.

ERROR:  missing FROM-clause entry for table "vars" 
LINE 12: and start_date <=  DATE(vars.calcdate) and end_date >= DATE(v...
                                 ^

如果vars.calcdatevars.salary更改为常量,那么SQL工作正常。我认为这与vars.语法或用法有关。

1 个答案:

答案 0 :(得分:1)

我找到了解决方案。这是我想的语法。不允许使用vars.name的格式(不确定我在哪里看到)。

WITH vars AS ( SELECT
  DATE('2018-01-07') AS calcdate,
  12345 AS salary
)
select *
from taxes
where country_alpha3='USA' and year='2018' and active=true
and subdivision_code='US-MEDI'
and local_code is null
and start_date <= (SELECT calcdate from vars) and end_date >= (SELECT calcdate from vars)
and lower_amount_cents <= (SELECT salary from vars) and upper_amount_cents >= (SELECT salary from vars);