我必须在postgresql中编写一个程序,它将找到具有字母数字值(文本)的列的最大值,如'RAM-1','RAM-2'

fcwjkofz  于 2023-04-20  发布在  PostgreSQL
关注(0)|答案(2)|浏览(68)

我有一个列名为Item_code,其值为'RAM-1','RAM-2','RAM-2'....'RAM-12'.我必须在PostgreSQL中编写程序,从中找到最大值。

CREATE OR REPLACE FUNCTION public.get_last_itemcode(
item text)
RETURNS text
LANGUAGE 'plpgsql'
COST 100
VOLATILE PARALLEL UNSAFE
AS $BODY$
declare 
result text;      
BEGIN
   Select MAX(it.item_code) into result from public.items as it where it.item_name = item;

   return result;
END;
$BODY$;

但它给出的值最大值为“RAM-9”,而不是“RAM-15”。

gz5pxeao

gz5pxeao1#

以下各项应满足规定的要求:

CREATE OR REPLACE FUNCTION get_last_itemcode(item items.item_name%type)
  RETURNS items.item_code%type
  LANGUAGE plpgsql
  STRICT
  AS $BODY$
DECLARE
  last_itemcode items.item_code%type;
BEGIN
  SELECT items.item_code
    INTO last_itemcode
    FROM items
   WHERE items.item_name = get_last_itemcode.item
   ORDER BY regexp_replace(items.item_code, '^.*-(\d+)$', '\1')::integer DESC
   LIMIT 1;

  RETURN last_itemcode;
END
$BODY$;

已指定STRICT,因为如果 item 为NULL,则函数将始终返回NULL。查询中的所有列和变量引用都经过限定,以防止名称冲突。类型声明引用相关的表列,以帮助防止不兼容的架构更改。

q3qa4bjr

q3qa4bjr2#

要获得最大值,您需要按照从item_code中提取的数字对记录进行降序排列,然后使用LIMIT 1获取第一个:

CREATE OR REPLACE FUNCTION public.get_last_itemcode(item text)
RETURNS text
LANGUAGE 'plpgsql'
COST 100
VOLATILE PARALLEL UNSAFE
AS $BODY$
declare 
result text;      
BEGIN
   Select item_code into result
   from public.items 
   where item_name = item
   order by REGEXP_REPLACE(item_code, '.*-(^0-9)*', '\1')::int desc
   limit 1;

   return result;
END;
$BODY$;

Demo here

相关问题