将列更改为行

时间:2015-02-12 12:33:47

标签: sql-server-2008 multiple-columns

我有以下脚本:

SELECT DISTINCT [L_ID] 
      ,[tTerminal].[C_Name]
      ,[C_Place]
      ,CAST(CAST([B_SubBranch]AS BINARY) AS VARCHAR(20)) AS SubBranch1 
      ,ISNULL(( SELECT c_name FROM [cOffice] WHERE c_code = CAST(CAST([B_SubBranch]AS BINARY) AS VARCHAR(20))),'') AS SBname1 

      ,CAST(CAST(SUBSTRING([B_SubBranch],31, 31)AS BINARY) AS VARCHAR(20)) AS SubBranch2
      ,ISNULL(( SELECT c_name FROM [cOffice] WHERE c_code = CAST(CAST(SUBSTRING([B_SubBranch],31, 31)AS BINARY) AS VARCHAR(20))),'') AS SBname2 

  FROM [tTerminal], [cOffice] ORDER BY [L_ID]

其中给出了以下结果

L_ID    C_Name              C_Place                SubBranch1  SBname1                             SubBranch2   SBname2
4200    000042 VTerminal    Sr Windhoek 000042     20048       Meat Market Windhoek 020048         45395        Hungry Lion Windhoek  045395        
4201    000042 Virdi 4000   Sr Windhoek 000042     20048       Meat Market Windhoek 020048         45395        Hungry Lion Windhoek 045395     
8400    000084 VTerminal    Sr Swakopmund 000084   20080       Meat Market Swakopmund 020080       31314        Hungry Lion Swakopmund 031314       
8401    000084 Virdi 4000   Sr Swakopmund 000084   20080       Meat Market Swakopmund 020080       31314    Hungry Lion Swakopmund 031314       
11500   000115 VTerminal    Sr Vryburg 000115      20111       Meat Market Vryburg 020111               
11501   000115 Virdi 4000   Sr Vryburg 000115      20111       Meat Market Vryburg 020111               

我希望脚本能够做到这一点:

 L_ID   C_Name              C_Place                SubBranch  SBname                               
 4200   000042 VTerminal    Sr Windhoek 000042     20048       Meat Market Windhoek 020048         
 4200   000042 VTerminal    Sr Windhoek 000042     45395       Hungry Lion Windhoek  045395 
 4201   000042 Virdi 4000   Sr Windhoek 000042     20048       Meat Market Windhoek 020048          
 4201   000042 Virdi 4000   Sr Windhoek 000042     45395       Hungry Lion Windhoek 045395      

基本上,不是每次都为“分支”创建一个新列,而是为每个分支创建一个下面的行。 我尝试将它们全部重命名为相同的列名,但它只是创建了重复的列名。请帮忙!

1 个答案:

答案 0 :(得分:0)

你可以尝试的几件事:

  • 删除DISTINCT和CAST
  • 将ORDER BY扩展为:L_ID,C_Name,C_Place,SubBranch

否则你不得不潜入更复杂的GROUP BY,子查询和转向世界......