문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top