我正在使用PostgreSQL 9.6,其查询大致如下所示:
DO $$
DECLARE max_sales_date DATE ;
BEGIN
max_sales_date :=
select sales_date::date
from (
select count(sales_date::date)
, sales_date::date
, row_number() over (order by count(sales_date::date) desc) as rn
from Sales
group by sales_date::date
) a where a.rn = 1 ;
select *
from Sales
where sales_date = max_sales_date ;
END $$ ;
正如您所看到的,我希望获得销售数量最多的一天,将其存储在变量中并在另一个查询中使用它。我知道在这种情况下不需要变量,但我需要这个用于尚未开始开发的另一个步骤。
DBeaver 5.0很遗憾地抛出以下错误消息:
内部jdbc驱动程序错误
java.lang.ArrayIndexOutofBoundsExcception:
我还必须提到结果存储在变量中的查询在独立使用时工作正常。
因此我有两个问题:
答案 0 :(得分:-1)
你可以使用select ... into pattern,你不能选择"选择*"在DO函数中查询 - 它不是要返回查询。
DO $$
DECLARE max_sales_date DATE ;
declare sale record;
BEGIN
select sales_date into max_sales_date from
(select sales_date from (select count(sales_date) as cnt, sales_date::date
from Sales group by sales_date) as dt order by cnt desc limit 1) as ct;
for sale in select * from Sales where sales_date = max_sales_date
loop
-- do whatever is needed with this data
end loop;
END $$ ;