SQL将多行组合成一行

时间:2013-09-16 13:28:48

标签: sql sql-server sql-server-2008 odbc sqlanywhere

我想要做的是将与VhStock.No相关联的所有工作代码合并为一行。列WkRoDesc.Job_Code END AS WorkNeeded,其中包含所有作业代码,但下面列出的四个用','分隔,然后在另一列中以相同的方式组合这四个作业代码。

SELECT 
--other things selected here
vhstock.No AS [Tag #], 
WkInvReg.Ro_Number

CASE WHEN WkRoDesc.Job_Code = 'Outside AOR' 
         OR WkRoDesc.Job_Code = 'AOR Del'
         OR WkRoDesc.Job_Code = 'AOR L & G'
         OR WkRoDesc.Job_Code = '/Cust PU/D'
    THEN NULL ELSE WkRoDesc.Job_Code END AS WorkNeeded,
  CASE WHEN WkRoDesc.Job_Code = 'Outside AOR' 
         OR WkRoDesc.Job_Code = 'AOR Del'
         OR WkRoDesc.Job_Code = 'AOR L & G'
         OR WkRoDesc.Job_Code = '/Cust PU/D'
    THEN WkRoDesc.Job_Code ELSE NULL END AS DPO



FROM vhstock, WkInvReg, WkRoDesc

WHERE vhstock.no = WkInvReg.Stock_No AND WkInvReg.Ro_Number = WkRoDesc.Ro_Number

我正在使用带有ODBC连接的SQL Server 08 R2来从SQL Anywhere v.11数据库进行查询。我使用Foresight Intelligence作为进行查询的界面。我没有直接访问任何一个数据库,因为它们由软件供应商管理。

我该怎么做?试过这个,但没有解释就收到错误

stuff((
    select ',' + WkRoDesc.Job_Code + ', '
    from WkRoDesc
    where WkRoDesc.Ro_Number = WkInvReg.Ro_Number
      and NOT (WkRoDesc.Job_Code = 'Outside AOR' OR WkRoDesc.Job_Code = 'AOR Del' OR WkRoDesc.Job_Code = 'AOR L & G' OR WkRoDesc.Job_Code = '/Cust PU/D')
   FOR xml path('')
    ), 1, 1, '') AS WorkNeeded,    

stuff((
    select ',' + WkRoDesc.Job_Code + ', '
    from WkRoDesc
    where WkRoDesc.Ro_Number = WkInvReg.Ro_Number
      and (WkRoDesc.Job_Code = 'Outside AOR' OR WkRoDesc.Job_Code = 'AOR Del' OR WkRoDesc.Job_Code = 'AOR L & G' OR WkRoDesc.Job_Code = '/Cust PU/D')
   FOR xml path('')
    ), 1, 1, '') AS DPO

1 个答案:

答案 0 :(得分:0)

你喜欢groupby吗?希望这有帮助

MAX(DISTINCT CASE WHEN WkRoDesc.Job_Code = 'Outside AOR' THEN WkRoDesc.Job_Code END) + ',' + MAX(DISTINCT CASE WHEN WkRoDesc.Job_Code ='AOR Del' THEN WkRoDesc.Job_Code END) 
                  + ',' + MAX(DISTINCT CASE WHEN WkRoDesc.Job_Code ='AOR L & G' THEN WkRoDesc.Job_Code END) + ',' + MAX(DISTINCT CASE WHEN WkRoDesc.Job_Code ='/Cust PU/D' THEN WkRoDesc.Job_Code END) 
                  AS WorkNeeded

结果是WorkNeeded = AOR之外,AOR Del,AOR L& G,/ Cust PU / D