sql - 寻找最高值(value)

标签 sql database postgresql plpgsql

我有一个函数,它接受两个值并返回 setof record,这是我的作业要求的。

现在我有一个不同的问题,我想使用这个函数,但不是返回一组记录,我想要这些选项之一,无论哪个更简单:

  • 返回一个表而不是一组。
  • 在调用函数之前创建一个表(名为“temp”的表),并用值填充它。

这是我的函数,它以月和年作为参数,并返回律师在该月和年处理的文件中必须支付的费用:

create or replace function calcbilling( cmonth int,  cyear int) returns setof record
as $$
declare r record;
begin
    for r in(select billing.fid, billing.lname, (lawyer.hbilling*billing.hours) as totpay
         from billing natural join lawyer
         where date_part('month',billing.bdate)=cmonth and date_part('year',billing.bdate)=cyear)
    loop

        return next r;
    end loop;
end;
$$language plpgsql;

最佳答案

函数返回表比原来的更简单(当然也更方便):

create or replace function calc_billing(cmonth int, cyear int) 
returns table (fid integer, lname text, totpay numeric)
as $$
begin
    return query
        select b.fid, b.lname, l.hbilling* b.hours as totpay
        from billing b
        natural join lawyer l
        where 
            date_part('month', b.bdate) = cmonth 
            and date_part('year', b.bdate) = cyear;
end;
$$language plpgsql;

-- use:
select * from calc_billing(1, 2016);

sql(而不是 plpgsql)变体更简单:

create or replace function calc_billing(cmonth int, cyear int) 
returns table (fid integer, lname text, totpay numeric)
as $$
    select b.fid, b.lname, l.hbilling* b.hours as totpay
    from billing b
    natural join lawyer l
    where 
        date_part('month', b.bdate) = cmonth 
        and date_part('year', b.bdate) = cyear;
$$language sql;

请注意,我更改了函数名称以使其更易于测试(没有名称冲突)。如有必要,请更改列类型以适合您的模型。

关于sql - 寻找最高值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38790918/

相关文章:

sql - Oracle中是否需要 'as'关键字来定义别名?

mysql - 在 MySQL 中使用 CASE/IF 语句

sql - 当我知道sql中每个簇中的点时计算簇数

php - PDO:lastInsertId返回什么值?

database - smallint 或 character(10) 哪个更有效?

python - 为什么我会收到带有 sqlalchemy 元数据的现有表的 "relation does not exist"错误?

java - 寻找以下代码的优化

PHP 选择语句不起作用?

mysql - 如何获取每个用户给出解决方案的多次平均值(查询)

java - 无法使用 Postgres 存储函数获取 ID - int 类型的值错误