how to use correctly if statement postgresql

﹥>﹥吖頭↗ 提交于 2021-02-11 05:58:35

问题


I'm trying to create a trigger that populates a table everytime X amount of rows are added to other table. The logic would be:

1- check how many rows are in table A based on last date on table B.
2- once there are 1000 rows in table A from the last date on table B, add one row to table B

Table A stores ticks from market and table B stores OHLC data (Open, High, Low, Close). Ticks have only 3 columns: date, bid and ask.

Open is the first known price, Low is the min price, High is the max price and Close is the last price. All this prices are calculated based on the last 1000 ticks using the bid column. So it would be:

  • Open: bid n°0
  • High: max bid between 0 and 999
  • Low: min bid between 0 and 999
  • Close: bid n° 999

The thing is that I'm trying to check if there are enough ticks to create a candle, and I'm trying to construct the trigger like this:

with total_ticks as (
    select count(*) from (
    select *  from eurusd_tick2 eurusd where date > 
        (SELECT date from eurusd_ohlc order by date desc limit 1) 
        order by date asc) totals)

This code actually gives me the total amount of ticks that are from the last known date. The problem comes here, because I'm trying to use "if" conditionals in order to start building the logic, but I only get syntax errors.

For example, I have tried

if 1000<total_ticks then 
   raise notice 'there are less than 1000'

or

if 1000 < select * from total_ticks then
   raise notice 'there are less than 1000'

How should I use the if statement? what I'm missing here? I have also tried something like:

DO $$
DECLARE
  a integer := 10;
  b integer := 20;
BEGIN 
  IF a > b THEN
    RAISE NOTICE 'a is greater than b';
  END IF;

  IF a < b THEN
    RAISE NOTICE 'a is less than b';
  END IF;

  IF a = b THEN
    RAISE NOTICE 'a is equal to b';
  END IF;
END $$;

But I get errors that says that there is an error near or at "DO".

I'm confused, so I would appreciate a little help on how to use this.


回答1:


To make it shorter a bit:

do $$
declare
  a integer := 10;
  b integer := 20;
  msg text;
begin
  msg := case
    when a>b then 'a is greater than b'
    when a<b then 'a is less than b'
    when a=b then 'a is equal to b'
    else 'NaN here'
  end;
  raise notice '%', msg;
end $$;

It obviously works in psql. Maybe something wrong with finance trading candlestick-chart



来源:https://stackoverflow.com/questions/61744527/how-to-use-correctly-if-statement-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!