簡體   English   中英

使用 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

我正在分組,但仍然需要一些聚合 function 以獲得可能看起來像這樣的所需結果:

| 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|

請注意,這里沒有聚合,沒有計數、平均或求和。 是否有另一個聚合 function 可以做到這一點?

如果我理解正確,您可以使用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;

暫無
暫無

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

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