2017-05-04 72 views
0

我想創建一個工作ID和列的列表,列出所有匹配的不同工作類別,但連接到同一列。作爲一個例子,現在工作82041有兩個類別,但現在返回兩行。我希望它能夠在一個領域內說「零售,銷售助理」。將多行數據合併到同一列

我試過的代碼如下,有人可以告訴我我做錯了什麼嗎?

例:

jobOrderID (No column name) 

82027 Motion Graphics    
82029 Other       
82030 Product Designer    
82041 Retail       
82041 Sales Associate    
82069 Social Media  

示例代碼:

select JobOrder.jobOrderID ,  
     stuff((select distinct ', ' + cast(Category.occupation as nchar(30)) 
       from Category 
       where Category.categoryID = JobOrderCategories.categoryID 
     for xml path ('')),1,1,'')  

from JobOrder 
left outer join JobOrderCategories 
    on JobOrder.joborderid = JobOrderCategories.jobOrderID 
left outer join Category 
    on Category.categoryID = JobOrderCategories.categoryID 

where JobOrder.dateAdded > '2017-5-2' and JobOrder.dateAdded < '2017-5-3' 
    and joborder.isDeleted = 0 

order by joborder.dateAdded asc 

回答

0

想通了通過改變左側加入

select 

JobOrder.jobOrderID, 

stuff((select distinct ', ' + cast(Category.occupation as varchar(30)) 
from Category 
left outer join JobOrderCategories on (Category.categoryID = JobOrderCategories.categoryID and joborder.jobOrderID = JobOrderCategories.joborderid) 
where Category.categoryID = JobOrderCategories.categoryID 
for xml path ('')),1,1,'') 


from JobOrder 

where JobOrder.dateAdded > '2017-5-2' and JobOrder.dateAdded < '2017-5-3' 
and joborder.isDeleted = 0 
+0

學習'format'用'{}你的代碼在'工具欄。 – Parfait

+0

感謝您的注意! –