1

这是我目前的数据:

GID, AppID, GName, GDesig, GBusinessName
101   3002   A     JO       AB House
102   3002   B     EO       BD Ltd

我需要提一下,行数可能是 1 到 4。我想这样显示这条记录:

GID, AppID, GName, GDesig, GBusinessName, GName, GDesig, GBusinessName
101   3002   A     JO       AB House      B      EO       BD Ltd

如何使用存储过程来做到这一点?如果有人给我任何解决方案,那将对我有所帮助。

谢谢

努尔

4

2 回答 2

1

您没有提到输出中每一行应该是唯一的。我认为应该是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 小提琴版本

于 2013-10-01T18:41:13.630 回答
0

您也可以使用数据透视表来实现结果

如何在 Transact/SQL 中创建数据透视表?

于 2013-10-01T19:02:25.910 回答