简体   繁体   中英

Returning the results of multiple 'WITH CTE' queries as one result

I am trying to select the highest price from the same product over n periods of time ie last 5, 50, 100, 500. At the moment I'm running the query four times for above periods like this:

;WITH CTE AS 
(
    SELECT TOP (500) * FROM Ticker WHERE ProductId='BTC-USD'
    ORDER BY ID DESC
)  SELECT TOP (1) * FROM CTE 
ORDER BY PRICE desc

Is there a way I can get all the results at once in 4 rows?

Hmmmm . . . My first thought is a union all :

with cte as (
      select top (500) t.*, row_number() over (order by id desc) as seqnum
      from Ticker t
      where ProductId = 'BTC-USD'
      order by id desc
     )
select 500 as which, max(cte.price) as max_price from cte where seqnum <= 500 union all
select 100 as which, max(cte.price) from cte where seqnum <= 100 union all
select 50 as which, max(cte.price) from cte where seqnum <= 50 union all
select 5 as which, max(cte.price) from cte where seqnum <= 5;

But, I have another idea:

with cte as (
      select top (500) t.*, row_number() over (order by id desc) as seqnum
      from Ticker t
      where ProductId = 'BTC-USD'
      order by id desc
     )
select v.which, x.max_price
from (values (5), (50), (100), (500)) v(which) cross apply
     (select max(price) as max_price from cte where seqnum <= which) x;

Of course, the "500" in the CTE needs to match the maximum value in v . You can actually get rid of the TOP in the CTE.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM