具有两个 select 语句的 PostgreSQL 函数

PostgreSQLFunction with two select statements

我正在尝试创建一个 PostgreSQL 函数,声明两个变量 return 每个变量都是不同查询的结果,查询本身非常简单,并且依赖于相同的 select条件不同:

select count (*) from editions where year >= '2000'

select count (*) from editions where year < '2000'

table的结构也很简单,一共有三行:

  1. 代码(数字)
  2. 版本(字符)
  3. 年份(整数)

如何创建这个函数?

这太基础了。我想你可以在 Google 中找到很多教程来创建这个 Function。你的 Year 列是 Integer 所以不要'像 String 使用 Single Quote..

函数 totalRecords1()

CREATE OR REPLACE FUNCTION totalRecords1()
RETURNS integer AS $total1$
declare
    total1 integer;
BEGIN
   SELECT count(*) into total1 
   FROM your_table
   WHERE year >= 2000;
   RETURN total1;
END;
$total1$ LANGUAGE plpgsql;

函数 totalRecords2()

CREATE OR REPLACE FUNCTION totalRecords2()
RETURNS integer AS $total2$
declare
    total2 integer;
BEGIN
   SELECT count(*) into total2 
   FROM your_table
   WHERE year < 2000;
   RETURN total2;
END;
$total2$ LANGUAGE plpgsql;

Select Statement

select totalrecords1(), totalrecords2();

你可以在DEMO

这里看到