2010-04-23 78 views
0

我有表中的SQL作爲號碼查詢

 
User | Account 
-----+--------- 
    1 | 25 
    1 | 31 
    1 | 35 
    1 | 44 
    1 | 50 
    1 | 59 

和輸出需要三列

 
    1 | 25 | 31 
    1 | 35 | 44 
    1 | 50 | 59 
+0

你的意思是,你需要在每一行中有兩個帳號? – Kangkan 2010-04-23 06:01:05

+0

是的,我需要每行有兩個帳戶 – Nisha 2010-04-23 06:04:33

+0

您正在使用哪個版本的SQL Server? SQL server 2000,2005或2008 – 2010-04-23 06:18:46

回答

1

好了,如u說,SQL Server 2005中,我會告訴你的實現使用rownumber。假設: 1.)基本組應該是Id。 ID 1和ID 2的帳戶不應位於同一行。

解決方案與模擬數據:

SELECT ID, 
     Max(Case When OrderCaluse = 0 Then Account Else NULL END) AS Account1, 
     Max(Case When OrderCaluse = 1 Then Account Else NULL END) AS Account2 
FROM 
( 
    Select ID, 
      Account, 
      (RowNum+1)/2 As GroupClause, 
      (RowNum+1)%2 as OrderCaluse 
    FROM 
    (
     Select *, 
       ROW_NUMBER() Over (Partition by Id order by account) As RowNum 
     FRom 
     (
      Select 1 as Id, 25 as Account 
      Union ALL 
      Select 1, 31 
      Union ALL 
      Select 1, 35 
      Union ALL 
      Select 1, 44 
      Union ALL 
      Select 1, 50 
      Union ALL 
      Select 1, 59 
     ) AS UserAccount 
    ) AS T 
) AS T1 
Group By Id,GroupClause 

結果:

1 25 31 
1 35 44 
1 50 59 

希望它能幫助。爲了您的使用,只需刪除Inner temp表UserAccount並使用您的物理表。