您没有提到输出中每一行应该是唯一的。我认为应该是AppId
。鉴于此,诀窍是Partition By
您为每个 AppId 分组对每一行进行排名。您要寻找的是交叉表。鉴于您说每个组最多可以有四行,我们可以从中构建一个静态交叉表。
;With RnkItems As
(
Select GID, AppId, GName, GDesig, GBusinessName
, Row_Number() Over ( Partition By AppId Order By GID, GName ) As Rnk
From SourceData
)
Select AppId
, Min( Case When Rnk = 1 Then GName End ) As GName1
, Min( Case When Rnk = 1 Then GDesig End ) As GDesig1
, Min( Case When Rnk = 1 Then GBusinessName End ) As GBusinessName1
, Min( Case When Rnk = 2 Then GName End ) As GName2
, Min( Case When Rnk = 2 Then GDesig End ) As GDesig2
, Min( Case When Rnk = 2 Then GBusinessName End ) As GBusinessName2
, Min( Case When Rnk = 3 Then GName End ) As GName3
, Min( Case When Rnk = 3 Then GDesig End ) As GDesig3
, Min( Case When Rnk = 3 Then GBusinessName End ) As GBusinessName3
, Min( Case When Rnk = 4 Then GName End ) As GName4
, Min( Case When Rnk = 4 Then GDesig End ) As GDesig4
, Min( Case When Rnk = 4 Then GBusinessName End ) As GBusinessName4
From RnkItems
Group By AppId
SQL 小提琴版本