我想在SQL Server中进行group_concat

时间:2017-08-12 05:00:14

标签: sql-server sql-server-2008

我知道group_concat在SQL Server 2008中不起作用,但我想group_concat

我的示例数据如下所示:

email address         | product code   
----------------------+---------------
garry123@gmail.com    | A123A  
garry123@gmail.com    | AB263    
ada121@hotmail.com    | 45632A   
ada121@hotmail.com    | 78YU
garry123@gmail.com    | 6543D 

我想要这个结果:

garry123@gmail.com | A123A,AB263,6543D 
ada121@hotmail.com | 45632A,78YU

我尝试过的代码:

SELECT
    c.EmailAddress,
    od.concat(productcode) as Product_SKU
FROM
    OrderDetails od
JOIN 
    Orders o ON od.OrderID = o.OrderID 
JOIN 
    Customers c ON c.CustomerID = o.CustomerID
WHERE
    o.OrderDate BETWEEN 01/01/2016 AND GETDATE()
GROUP BY 
    c.EmailAddress

我收到错误:

  

找不到列“od”或用户定义的函数或聚合“od.concat”,或者名称不明确。

但这不起作用。任何人都可以告诉我这样做的正确方法吗?

编辑后我正在尝试的代码:

SELECT
    c.EmailAddress,
    productcode = STUFF((SELECT ',' + od.productcode
                         FROM Orderdetails od
                         WHERE c.EmailAddress = od.EmailAddress
                         FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM
    OrderDetails od
JOIN 
    Orders o ON od.OrderID = o.OrderID 
JOIN 
    Customers c ON c.CustomerID = o.CustomerID
WHERE
    o.OrderDate BETWEEN 01/01/2016 AND GETDATE()

现在我收到了这个错误:

  

无效的列名称'EmailAddress'。

0 个答案:

没有答案