sql - 带有 CASE 的 Postgres 自定义函数

标签 sql postgresql case plpgsql

我有表 watchers:

------------------------------------------
time_type | time_count | timestamp_created
------------------------------------------
  'hour'  |   1        |   2016-12-08 15:56:26.169614
  'hour'  |   13       |   ... 
  'day'   |   5        |   ...

我尝试根据 time_typetime_count 值获取整数:

CREATE OR REPLACE FUNCTION af_calculate_range(tt text,tc  integer) RETURNS integer AS $$ 
            SELECT tt, CASE tt WHEN 'day' THEN tc * 60 * 60 
                               WHEN 'hour' THEN tc * 60
                       END
        FROM watchers;

          $$
    LANGUAGE SQL;

SELECT af_calculate_range(time_type, time_count) FROM watchers

但是我得到一个错误:

ERROR:  return type mismatch in function declared to return integer  
DETAIL:  Final statement must return exactly one column. 
CONTEXT:  SQL function "af_calculate_range"
********** Error **********

用法:

SELECT * FROM watchers
WHERE  EXTRACT(EPOCH FROM now()) > (EXTRACT(EPOCH FROM timestamp_created) +
 af_calculate_range(time_type, time_count) )

如果 time_type = 'hour'time_count = 1 输出应该是 3600 秒。

我的例子有什么问题:

我用了https://www.postgresql.org/docs/7.4/static/functions-conditional.html

https://www.postgresql.org/docs/9.1/static/sql-createfunction.html

最佳答案

一个函数只能返回一个值,所以你可能打算这样做:

CREATE OR REPLACE FUNCTION af_calculate_range(tt text, tc integer) RETURNS integer AS $$ 
        SELECT CASE WHEN tt = 'day' THEN tc * 60 * 60    -- return a (single) scalar 
                    WHEN tt = 'hour' THEN tc * 60
               END
        FROM watchers;
      $$
LANGUAGE SQL;

但正如@Mureinik 指出的那样,您甚至不需要执行SELECT;直接使用 CASE 表达式即可。

关于sql - 带有 CASE 的 Postgres 自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41209410/

相关文章:

mysql - 将垂直表转换为水平表

MySQL CASE 基于之前的 CASE 值

sql - 带 case 列的查询

sql - 如何将表从 Microsoft SQL Server 导出到 Excel?

python - Google bigquery python 客户端库 SQL 选择正则表达式错误

oracle - 从日期列中删除时间

sql - 如何按时间戳字段分组?

c# - 如何为连接到 SQL 数据库的项目创建安装文件?

"SELECT * FROM INTO FILE"中的 MySQL 语法问题

SQL:过滤行