Supabase user here trying to return a SQL query that groups share sales of a stock by the stock symbol. Essentially the user can make multiple purchases of the same stock for varying amount of shares. On a dashboard page, I want to show that as one combined row as a sum of all of their purchased stocks.
Another post remarks the Supabase API has no SUM operator, which means I would have to make a function, then run it using supabase.rpc(...)
.
Made the query (has desired results) and function (created successfully) but ran into the above error
Failed to run sql query: structure of query does not match function result type
while running the function.
Created table:
create table trades (
id bigint generated by default as identity primary key,
account_id bigint references accounts(id) not null,
symbol varchar(5) not null,
name text not null,
shares int not null,
price numeric not null,
inserted_at timestamp with time zone default current_timestamp not null
);
Created query (runs as desired):
SELECT name as grouped_name, symbol::text as grouped_symbol, price as grouped_price, SUM (shares) as grouped_sum
FROM trades
GROUP BY
name, symbol, price
ORDER BY
SUM (shares) DESC;
Created function with above query (successfully makes function):
CREATE or REPLACE function return_grouped_shares()
RETURNS table(grouped_name text, grouped_symbol text, grouped_price numeric, grouped_sum int) AS
$$
BEGIN
RETURN QUERY
SELECT name as grouped_name, symbol::text as grouped_symbol, price as grouped_price, SUM (shares) as grouped_sum
FROM trades
GROUP BY
name, symbol, price
ORDER BY
SUM (shares) DESC;
END
$$ LANGUAGE plpgsql;
Running function:
SELECT *
FROM return_grouped_shares ();
yields error
Failed to run sql query: structure of query does not match function result type
.
What's going on here?