sql—获取查询的最后一列,并将结果用逗号分隔成1列

j5fpnvbx  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(418)

我有一个sql server(2018)查询,其中最后一列( SP.name )可以有多个值,从而创建重复的行。我想把最后一列的结果放到1个字段中,用逗号分隔。
例如,如果下面查询的输出是(您将看到一个有野外考察,另一个有生日)。

John , Smith, x@Z.com,New York, NY,  11208 , Field Trip
John , Smith, x@Z.com,New York, NY,  11208 , Birthday Party

我希望它是这样的,实地考察和生日是在同一列。请注意,它可以是2个以上的结果,对于最后一列,有些查询最多会有5个结果。

John , Smith, x@Z.com,New York, NY,  11208 , "Field Trip,Birthday Party"

这是查询

SELECT DISTINCT 
   CC.FirstName, CC.LastName, CC.Email, Addresses.City, Addresses.State, Addresses.Postal, SP.Name
FROM CustContacts AS CC WITH (NoLock) 
INNER JOIN Orders AS O WITH (Nolock) ON CC.CustContactID = O.ContactID 
INNER JOIN Customers AS C WITH (Nolock) ON O.CustomerID = C.CustomerID 
INNER JOIN SalesPrograms AS SP WITH (NoLock) ON O.SalesProgramID = SP.SalesProgramID 
INNER JOIN OrderLines AS OL WITH (NoLock) ON O.OrderID = OL.OrderID 
INNER JOIN RMEvents AS RME WITH (NoLock) ON OL.EventID = RME.EventID 
INNER JOIN Addresses ON CC.AddressID = Addresses.AddressID 
LEFT OUTER JOIN OEGroupVisits AS GV WITH (NoLock) ON O.GroupVisitID = GV.GroupVisitID
9cbw7uwe

9cbw7uwe1#

你似乎不需要这么多人。虽然它们可能用于过滤,但它们似乎没有什么作用。
因为sql server 2016不支持 STRING_AGG() ,您可以使用 FOR XML 技巧:

SELECT CC.FirstName, CC.LastName, CC.Email, a.City, a.State, a.Postal,
       STUFF( (SELECT CONCAT(', ', SP.Name)
               FROM Orders O JOIN
                    SalesPrograms SP 
                    ON O.SalesProgramID = SP.SalesProgramID 
               WHERE CC.CustContactID = O.ContactID 
               FOR XML PATH ('')
              ), 1, 2, '') as names
FROM CustContacts CC JOIN
     Addresses a
     ON CC.AddressID = a.AddressID ;
g6ll5ycj

g6ll5ycj2#

您需要对以下表进行自联接:custcontacts、addresses和salesprPrograms中的某些或所有列:cc.firstname、cc.lastname、cc.email、addresses.city、addresses.state、addresses.posal、sp.name。接下来,您将需要连接这3个值:sp.name、'、'、sp1.name。这是假设您的self join中有salesprograms作为sp,salesprograms作为sp1。

相关问题