簡體   English   中英

作為一個結果返回多個“ WITH CTE”查詢的結果

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

我正在嘗試在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行中一次獲得所有結果?

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

當然,CTE中的“ 500”需要匹配v中的最大值。 您實際上可以擺脫CTE中的TOP

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM