SQL语句中的嵌套循环

时间:2019-04-15 16:21:17

标签: sql sql-server sql-server-2014 string-aggregation

我一直在尝试找出是否有一种方法可以在SQL语句中使用循环。

Select j.JobID, s.OrderNumber, 
(SELECT OperationID From Operations) as Operations  <--- This will cause multiple results
From Jobs j
Inner Join Sales s on j.JobID = s.SalesJobID
Where j.JobID = '123456-1-1'

这就是我们拥有的

JobID        OrderNumber    Operation
-----        -----------    ----------
1123456-1-1   TEST1         DEV
1123456-1-1   TEST1         APR
1123456-1-1   TEST1         CAT
1123456-1-1   TEST1         LFT
1123456-1-1   TEST1         PKG

试图做这样的事情。

JobID        OrderNumber    Operations
-----        -----------    ----------
1123456-1-1   TEST1         DEV, APR, CAT, LFT, PKG

1 个答案:

答案 0 :(得分:0)

您可以使用XML PATH完成此操作

Select j.JobID, s.OrderNumber, 
(SELECT OperationID + ',' From Operations WHERE add_your_filter_here FOR XML PATH ('')) as Operations
From Jobs j
Inner Join Sales s on j.JobID = s.SalesJobID
Where j.JobID = '123456-1-1'