Pergunta

I would like to do something like this:

CNT=2;

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

This does not work, Firebird does not allow :cnt as a parameter to FIRST. I need to average the first CNT newest prices. The number 2 changes so it can not be hard-coded.

This can be broken out into a FOR SELECT loop and break when a count is reached. Is that the best way though? Can this be done in a single SQL statement?

Creating the SQL as a string and running it is not the best fit either. It is important that the database compile my SQL statement.

Foi útil?

Solução

You don't have to use CTE, you can do it directly:

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

Outras dicas

You can use a CTE (Common Table Expression) (see http://www.firebirdsql.org/refdocs/langrefupd21-select.html#langrefupd21-select-cte) to select data before calculate average. See example below:

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

select avg(price) from query1
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top