透视所需的帮助(SQL Server 2005)

时间:2010-05-25 02:47:23

标签: sql-server-2005

我有一张像

这样的表格
ID  Grps    Vals
--- ----    -----
1   1   1
1   1   3
1   1   45
1   2   23
1   2   34
1   2   66
1   3   10
1   3   17
1   3   77
2   1   144
2   1   344
2   1   555
2   2   11
2   2   22
2   2   33
2   3   55
2   3   67
2   3   77

所需的输出

ID  Record1     Record2     Record3
--- -------     -------     -------
1   1       23      10      
1   3       34      17      
1   45      66      77
2   144     11      55
2   344     22      67
2   555     33      77

我尝试过(使用while循环),但程序运行缓慢。我被要求通过使用基于SET的方法这样做。到目前为止,我的方法是

SELECT  ID,[1] AS [Record1], [2] AS [Record2], [3] as [Record3]
    FROM (  
    Select 
        Row_Number() Over(Partition By ID Order By Vals) records
        ,* 
        From myTable)x
    PIVOT
  (MAX(vals) FOR Grps IN ([1],[2],[3])) p

但它没有用。

任何人都可以帮忙解决这个问题。(SQL SERVER 2005)

3 个答案:

答案 0 :(得分:2)

你快到了!我所要做的就是在Partition By和Order By子句中添加必要的列,它起作用了:

SELECT  ID,[1] AS [Record1], [2] AS [Record2], [3] as [Record3] 
    FROM (   
    Select  
        Row_Number() Over(Partition By id, grps Order By id, grps, vals) records 
        ,*  
        From myTable)x 
    PIVOT 
  (MAX(vals) FOR Grps IN ([1],[2],[3])) p 

答案 1 :(得分:0)

一种不涉及使用PIVOT的简单方法就像:

;With ItemGroups As
    (
    Select Id, Grps, Vals 
        , Row_Number() Over ( Partition By Id, Grps Order By Vals ) As RowNum
    From myTable
    )
Select Id
    , Max( Case When Grps = 1 Then Vals End )
    , Max( Case When Grps = 2 Then Vals End )
    , Max( Case When Grps = 3 Then Vals End )
From ItemGroups
Group By Id, RowNum
Order By Id

答案 2 :(得分:0)

这可能不适用于您,但如果您使用像...这样的while循环

while( x<Total.length() ){
....do something
}

you should declare Total.length outside of the loop assigned to a variable...

int spoon= Total.length();
while( x< spoon ){
....do something
}

或者

每次循环运行时计算Total.length()的数量