在Firebird中,如何聚合前N行?

时间:2013-06-23 19:15:22

标签: firebird firebird2.5

我想做这样的事情:

CNT=2;

//[edit]
select avg(price) from (
  select first :CNT p.Price
  from Price p
  order by p.Date desc
);

这不起作用,Firebird不允许:cnt作为FIRST的参数。我需要平均第一个CNT最新价格。数字2会发生变化,因此无法进行硬编码。

这可以分解为FOR SELECT循环,并在达到计数时中断。这是最好的方式吗?这可以在一个SQL语句中完成吗?

将SQL创建为字符串并运行它也不是最合适的。数据库编译我的SQL语句非常重要。

2 个答案:

答案 0 :(得分:3)

您不必使用CTE,您可以直接进行:

select avg(price) from (
  select first :cnt p.Price
  from Price p
  order by p.Date desc
);

答案 1 :(得分:1)

您可以使用CTE(公用表表达式)(参见http://www.firebirdsql.org/refdocs/langrefupd21-select.html#langrefupd21-select-cte)在计算平均值之前选择数据。 见下面的例子:

with query1 as (
  select first 2 p.Price
  from Price p
  order by p.Date desc
)

select avg(price) from query1