Question

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.

Était-ce utile?

La solution

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
);

Autres conseils

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top