创建sql,它会给我用分号分隔的产品名称?

时间:2011-07-14 15:53:00

标签: sql sql-server-2008

我有一个如下的产品表。我想创建一个sql,它将为我提供以分号分隔的产品名称。

ProductName  AccountExpert
--------------------------
Tea          JohnSmith
Banana       GarySulvan
Water        JohnSmith
Candy        BobbySimmons
ConfecItem   BobbySimmons
Bread        JohnSmith
Soda         JohnSmith

Sql输出应该是这样的

AccountExpert  Products
-----------------------
JohnSmith      Tea; Water; Bread; Soda
GarySulvan     Banana
BobbySimmons   Candy; ConfecItem

4 个答案:

答案 0 :(得分:1)

如果您使用的是MySQL,请使用GROUPing和GROUP_CONCAT:

SELECT AccountExpert, GROUP_CONCAT(ProductName SEPARATOR '; ')
FROM ProductExperts
GROUP BY AccountExpert

答案 1 :(得分:1)

您可以尝试其中一些想法:

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

总的来说,在SQL-Server 2008中没有一种非常优雅的方法来实现这一点

答案 2 :(得分:1)

使用MS SQL,您可以使用FOR XML,使用Stuff函数删除多余的分隔符。不幸的是,没有像MySQL一样的组连接功能。

CREATE TABLE #ProductExpert (ProductName nvarchar(20), AccountExpert nvarchar(20))

INSERT INTO #ProductExpert(ProductName, AccountExpert) SELECT
'Tea',          'JohnSmith'     UNION ALL SELECT
'Banana',       'GarySulvan'    UNION ALL SELECT
'Water',        'JohnSmith'     UNION ALL SELECT
'Candy',        'BobbySimmons'  UNION ALL SELECT
'ConfecItem',   'BobbySimmons'  UNION ALL SELECT
'Bread',        'JohnSmith'     UNION ALL SELECT
'Soda',         'JohnSmith'

SELECT DISTINCT
    ae.AccountExpert,
    Stuff((
        SELECT
             '; ' + p.ProductName
        FROM
            #ProductExpert AS p
        WHERE
            ae.AccountExpert = p.AccountExpert
        ORDER BY
            p.ProductName
        FOR XML PATH('')
    ), 1, 2, '') AS Products
FROM
    #ProductExpert AS ae
ORDER BY
    ae.AccountExpert

DROP TABLE #ProductExpert

答案 3 :(得分:0)

请查看http://blog.namwarrizvi.com/?p=140

你想做什么,但用,而不是

相关问题