使用 rank() 获取最后和第一条记录

Get last and first record using rank()

我需要从 table 中获取某些 SSID 的第一条和最后一条记录(按 Date 列排序)。如果有更多具有相同最大或最小日期的记录,这不是问题。我只需要 union all.

我正在获取具有 max(date) 的最后一条记录:

with c as (
    select *, rnk = rank() over (partition by Date order by Date ASC)
    from table
    where SSID = '00921834800'
)
select top 1 Date, City, Title
from c
order by Date desc

如何在不再次使用排名的情况下使用单个 select 获得第一条记录 (min(Date))(仅与 order by Date asc 相同)?

我正在使用 MSSQL 2017。

; with c as (
    select *,
      rnk = rank() over (partition by Date order by Date ASC),
      rnk2 = rank() over (partition by Date order by Date desc)
    from table
    where SSID= '00921834800'
)
select Date,
City,
Title
from c
where rnk = 1 or rnk2 = 1
order by Date desc

我将使用以下查询:

select * from (select top 1 with ties * from t where ssid = '00921834800' order by date) as a
union all
select * from (select top 1 with ties * from t where ssid = '00921834800' order by date desc) as b

另一个解决方案是:

with 
c as 
(
select *, 
       rank() over (partition by Date order by Date ASC) AS RNK,
       count() OVER (partition by Date) AS CNT
from   table
where  SSID= '00921834800')
select Date, City, Title 
from   c
WHERE  RNK = 1
   OR  CNT = RNK
order by Date desc