代码之家  ›  专栏  ›  技术社区  ›  alwaysVBNET

将多个“with cte”查询的结果作为一个结果返回

  •  1
  • alwaysVBNET  · 技术社区  · 6 年前

    我想从同一种产品中选择最高的价格 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 回复  |  直到 6 年前
        1
  •  2
  •   alwaysVBNET    6 年前

    嗯。…我的第一个想法是 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 . 你真的可以摆脱 TOP 在CTE中。