存储过程从多行到多列

时间:2013-10-01 18:07:23

标签: sql-server-2008

这是我目前的数据:

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

如何使用存储过程执行此操作?如果有人给我任何解决方案,那对我有帮助。

由于

诺尔

2 个答案:

答案 0 :(得分: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 Fiddle version

答案 1 :(得分:0)

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

How to create a PivotTable in Transact/SQL?