Gag*_*ala 3 postgresql types function postgresql-9.5
下面是我的 sell_quantity 的表结构(迁移文件)
alter table public.invoice_item add column sold_quantity int4 default 1;
Run Code Online (Sandbox Code Playgroud)
下面是执行的函数
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; $$
Run Code Online (Sandbox Code Playgroud)
我的代码有什么问题,请帮我解决这个错误
返回类型 bigint 与第 3 列中的预期类型整数不匹配
小智 9
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)
Run Code Online (Sandbox Code Playgroud)