SQL语句中的嵌套循环[重复]

问题描述 投票:0回答:1

我一直试图弄清楚是否有一种方法可以在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
sql sql-server sql-server-2014 string-aggregation
1个回答
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'
© www.soinside.com 2019 - 2024. All rights reserved.