下面是我的sold_quantity(迁移文件)的表结构
alter table public.invoice_item add column sold_quantity int4 default 1;
下面是执行功能
CREATE OR REPLACE FUNCTION sold_quantity()
RETURNS TABLE(
invoiceid BIGINT,
itemid BIGINT,
sum_sold_quantity INT)
AS $$
BEGIN
RETURN QUERY SELECT
invoice_id as invoiceid, item_id as itemid, sum(sold_quantity) as
sum_sold_quantity
FROM
invoice_item
WHERE
status='sold'
GROUP BY
invoice_id, item_id;
END; $$
我的代码有什么问题,请帮助我解决此错误
返回的类型bigint与第3列中的预期类型整数不匹配
答案 0 :(得分:1)
sum()
返回bigint,不一定返回要求和的列的类型。
如果您100%确定总和不会超出整数范围,则可以在查询中使用强制转换来解决此问题:sum(sold_quantity)::int as sum_sold_quantity
但是最好调整函数的签名:
CREATE OR REPLACE FUNCTION sold_quantity()
RETURNS TABLE(
invoiceid BIGINT,
itemid BIGINT,
sum_sold_quantity BIGINT)