如何使用分区将 min/max 值转置到 SQL 服务器中的列?

How to transpose min/max value to columns in SQL Server using Partition?

我想从特定值中获取 MIN 和 MAX,并将它们放在彼此相邻的列中。这是我的查询,但我不知道如何转置这些值...

SELECT *
    , MIN([CID]) OVER (PARTITION BY [TID] ORDER BY [TID]) MinID
    , MAX([CID]) OVER (PARTITION BY [TID] ORDER BY [TID]) MaxID

鉴于:

TID       CID DATE
123456789 1   01JAN
123456789 2   02JAN
123456789 3   03JAN
123456789 4   04JAN

结果:

TID       CID DATE   MIN MAX DATEMIN DATEMAX
123456789 1   01JAN  1   4   01JAN   04JAN

这里简单聚合还不够好吗?

select 
    tid,
    min(cid) min_cid,
    max(cid) max_cid,
    min(date) min_date,
    max(date) max_date
from mytable
group by tid

或者,如果 ciddate 没有相应变化,您可以使用条件聚合:

select
    tid,
    max(case when rn_asc  = 1 then cid end) cid_at_min_date,
    max(case when rn_desc = 1 then cid end) cid_at_max_date,
    min(date) min_date,
    max(date) max_date

from (
    select 
        t.*,
        row_number() over(partition by tid order by cdate asc ) rn_asc,
        row_number() over(partition by tid order by cdate desc) rn_desc
    from mytable t
) t
where 1 in (rn_asc, rn_desc)
group by tid

这按 cdate 排序记录,并为您提供对应于最小和最大日期的 cid。如果您想要反过来,您可以轻松地调整查询(基本上,切换 cidcdate)。