使用 T-SQL 在没有聚合的情况下将多行转置为多列

Transpose multiple rows to multiple columns with no aggregate using T-SQL

用户有多个证书,可能属于 3 种不同类型。他们可能持有这些类型的多个证书。我想将它们放入一个记录中,预计每种类型最多有五个证书。 我编写了一个查询,该查询将查找类型并将其信息放入适当命名的列中,但每个证书仍获得一行。 数据形状为:

Name, cert_Type, Cert Name, cert_State, Cert_Expiration
JOE, Equipment, NULL, Operator, 01/30/2022
JOE Equipment, Rigger, 12/31/2021
JOE License, Maryland, 08/12/2025

我正在做一个分组,但仍然需要一些聚合函数来获得可能如下所示的期望结果:

| UserName| userID|Cred_Type_1|Cred_1|Type_1_Cred_1_ Expires|Type_1_Cred_2|Type_1_Cred_2_Expires|Cred_type_2|Type2_State |Type_2_expires|
| ----------- | ----------- |-------------|-------------|------------|------------|-----------|-----------|---|---|
|Joe|123|Equipment|Operator|01/30/2022|Rigger|12/31/2021|License | Maryland|08/12/2025|

注意这里没有聚合,不是计数、平均或求和。是否有另一个聚合函数可以执行此操作?

如果我没理解错的话,可以使用row_number()和条件聚合:

select userid, username,
       max(case when seqnum = 1 then cert_type end),
       max(case when seqnum = 1 then cert_name end),
       max(case when seqnum = 1 then cert_state end),
       max(case when seqnum = 1 then cert_expiration end),
       max(case when seqnum = 2 then cert_type end),
       max(case when seqnum = 2 then cert_name end),
       max(case when seqnum = 2 then cert_state end),
       max(case when seqnum = 2 then cert_expiration end),
       max(case when seqnum = 3 then cert_type end),
       max(case when seqnum = 3 then cert_name end),
       max(case when seqnum = 3 then cert_state end),
       max(case when seqnum = 3 then cert_expiration end),
from (select t.*,
             row_number() over (partition by userid order by cert_expiration desc) as seqnum
      from t
     ) t
group by userid, username;