【发布时间】:2017-08-21 06:48:26
【问题描述】:
我是新手,正在尝试使用以下代码创建一个函数:
CREATE OR REPLACE FUNCTION public.get_bulan()
returns table (request_detail timestamp with time zone)
language plpgsql stable
as $function$
begin
return query
select
case
when (extract(DAY FROM now()) >= 25) then generate_series(date_trunc('year', now()), date_trunc('day', now()) ,interval '1 month')
when (select extract(month FROM now()) = 2) then now() - (interval '1' month * generate_series(0,1))
when (select extract(month FROM now()) = 1) then now() - (interval '1' month * generate_series(0,2))
else generate_series((select date(date_trunc('year', now()))), (select date(now())-'1 month'::interval), interval '1 month')
end
order by timetstamptz(request_detail) desc;
end;
$function$;
上面查询的结果是:
2017-01-01 00:00:00
2017-02-01 00:00:00
2017-03-01 00:00:00
2017-04-01 00:00:00
2017-05-01 00:00:00
2017-06-01 00:00:00
2017-07-01 00:00:00
我尝试使用order by desc 和order by timestamp desc,但它不起作用。我想按降序排列,所以我得到了从 2017-07-01 到 2017-01-01 的结果。我该怎么做?
【问题讨论】:
-
好兄弟,你要程序还是明确查询?
-
程序呢?
-
你得到的结果有什么问题?对我来说看起来排序正确。
-
request_detail 会在结果中丢失,因此需要为 @a_horse_with_no_name 添加一个名称
-
是的,谢谢先生 :)
标签: sql postgresql sql-order-by plpgsql set-returning-functions