如何在psql中用declare或with子句包装表达式?

问题描述 投票:0回答:1

使用 psql 变量在集合中存储表达式:

\set vix round(100*(high/nullif(low,0)-1),2)

在 select 中调用变量:

select  :vix as vix from quote 
    where date='2023-12-08'  and :vix is not null 
    order by :vix desc  
    limit 10;

它打印如下输出:

   vix   
---------
 1466.53
  502.94
  167.57
  163.67
  150.00
  150.00
  141.13
  133.33
  105.58
  100.00
(10 rows)

在声明中调用变量

vix

DO $$
    DECLARE vix float := round(100*(high/nullif(low,0)-1),2);
BEGIN
    select  vix as vix from quote 
    where date='2023-12-08'  and vix is not null 
    order by vix desc  
    limit 10;
END $$;

遇到错误:

ERROR:  column "high" does not exist
LINE 1: SELECT round(100*(high/nullif(low,0)-1),2)
                          ^
QUERY:  SELECT round(100*(high/nullif(low,0)-1),2)
CONTEXT:  PL/pgSQL function inline_code_block line 3 during statement block local variable initialization
Time: 0.604 ms

将其放入 with 子句中:

WITH  vix as (
   round(100*(high/nullif(low,0)-1),2)
)
select  vix as vix from quote 
where date='2023-12-08'  and vix is not null 
order by vix desc  
limit 10;

遇到错误:

ERROR:  syntax error at or near "round"
LINE 2:    round(100*(high/nullif(low,0)-1),2)

如何修复它们?

postgresql with-statement declare
1个回答
0
投票

我认为你想要的是一个子查询来添加“虚拟”列:

WITH temp as (
  SELECT *, round(100*(high/nullif(low,0)-1),2) AS vix
  FROM quote
)
SELECT *
FROM temp
WHERE date = '2023-12-08'
  AND vix IS NOT NULL
ORDER BY vix DESC
LIMIT 10;

SELECT *
FROM (
  SELECT *, round(100*(high/nullif(low,0)-1),2) AS vix
  FROM quote
) AS temp
WHERE date = '2023-12-08'
  AND vix IS NOT NULL
ORDER BY vix DESC
LIMIT 10;
© www.soinside.com 2019 - 2024. All rights reserved.