如何在sql的内连接语句中使用COALESCE

时间:2016-06-22 00:12:01

标签: mysql sql-server inner-join coalesce

我计划在我的问题中使用COALESCE。我想要的只是在一列中用逗号分隔值。 这是我的发言:

select p.[name], cd.CustomerName, cd.CustomerEmailID
   ,cd.CustomerPhoneNo,cd.CustomerAddress
   ,cd.TotalPrice,cd.OrderDateTime, cd.PaymentMethod 
FROM CustomerDetails cd 
Inner Join CustomerProducts cp ON cp.CustomerID = cd.Id 
Inner Join Products p ON cp.ProductID = p.ProductID

它会给我这个

enter image description here

现在我希望产品列的结果为

carbon dioxied,industrial oxygen

因为它们具有相同的ID。

请帮帮我。非常感谢你

更新:小提琴 enter image description here

更新:当前声明,但仍然给我相同的结果。

use ShoppingCartDB
select 
      STUFF((SELECT ',' + p.[name]
             FROM  Products p
             WHERE cp.ProductID = p.ProductID
             FOR XML PATH(''),TYPE).value('.','nvarchar(max)'),1,1,'') AS Name
     , cd.CustomerName, cd.CustomerEmailID
     ,cd.CustomerPhoneNo,cd.CustomerAddress
     ,cd.TotalPrice,cd.OrderDateTime, cd.PaymentMethod 
FROM CustomerDetails cd 
Inner Join CustomerProducts cp ON cp.CustomerID = cd.Id 

1 个答案:

答案 0 :(得分:0)

SELECT DISTINCT
      STUFF((SELECT ',' + p.[name]
             FROM  Products p
             WHERE cp.ProductID = p.ProductID
             FOR XML PATH(''),TYPE).value('.','nvarchar(max)'),1,1,'') AS Name
     , cd.CustomerName, cd.CustomerEmailID
     ,cd.CustomerPhoneNo,cd.CustomerAddress
     ,cd.TotalPrice,cd.OrderDateTime, cd.PaymentMethod 
FROM CustomerDetails cd 
Inner Join CustomerProducts cp ON cp.CustomerID = cd.Id