Postgresql

如何在 postgresql 中創建一個帶有兩個參數的函式以從列表中返回計數?

  • April 29, 2021

我正在嘗試使用表中的兩個參數 year 和 code 執行一個函式,以返回給定程式碼和年份的計數。表是這樣的:

CREATE TABLE orders (
   id INT NOT NULL, 
   code INT NOT NULL, 
   service_id INT NOT NULL, 
   status CHARACTER VARYING(50), 
   creation TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
   status_date TIMESTAMP,
   created_user INT
   );

我能夠使用下面的函式返回計數,但是當我為年份和沒有計數的程式碼提供值時,它返回 NULL 但應該返回零,我該怎麼做?:

CREATE OR REPLACE FUNCTION yearly_orders
   (year INT, order_cat orders.code%type) RETURNS INT AS $$
   
DECLARE
   total INT DEFAULT 0;
   
BEGIN
   SELECT COUNT(orders.code) INTO total
   FROM orders
   WHERE status = 'Requested' AND EXTRACT(YEAR FROM creation) = year::INT AND orders.code = order_cat
   GROUP BY year, orders.code;
   RETURN total;
END;
$$LANGUAGE plpgsql;

數據類似於:

INSERT INTO orders 
(id, code, service_id, status, creation, status_date, created_user) 
VALUES 
(100,2394,558151,'Requested','2019-06-16 11:12','2019-06-18 14:08',1);

這會起作用:

CREATE OR REPLACE FUNCTION yearly_orders(_year int, _order_cat int)
 RETURNS int
 LANGUAGE sql STABLE AS
$func$
SELECT count(*)::int
FROM   orders o
WHERE  o.status = 'Requested'
AND    o.creation >= to_timestamp(_year::text, 'YYYY')
AND    o.creation <  to_timestamp((_year + 1)::text, 'YYYY')
AND    o.code = _order_cat;
$func$;

integerto的轉換timestamp實際上取決於您傳遞的確切內容以及它應該意味著什麼。您可能想要to_timestamp(_year::text, 'YY')

考慮一下 Akina 評論中的列表。

開始閱讀有關SQL 函式的手冊。

之後看看PL/pgSQL 函式

概述:

引用自:https://dba.stackexchange.com/questions/290693