返回多个' WITH CTE'的结果。查询作为一个结果

时间:2018-06-06 16:42:20

标签: sql sql-server

我试图在n段时间内选择同一产品的最高价格,即最后5,50,100,500。 目前,我在上述期间运行查询四次,如下所示:

;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

有没有办法可以在4行中同时获得所有结果?

1 个答案:

答案 0 :(得分:2)

嗯,嗯。 。 。我的第一个想法是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;

但是,我有另一个想法:

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;

当然,&#34; 500&#34;在CTE中需要匹配v中的最大值。你实际上可以摆脱CTE中的TOP