多个结果查询作为新列中的csv字符串

时间:2011-03-31 14:17:13

标签: sql linq-to-sql sql-server-2008

我有3张桌子:

用户,产品user2product

每个产品都有ID。

是否可以编写查询,其中我将得到2列:

UserID, Products

在产品列中,我将所有产品通过用逗号分隔的user2product表连接到用户。

2 个答案:

答案 0 :(得分:0)

我们在谈论什么是SQL-Dialect? 对于postgresql,这里有一个非常全面的答案: How to concatenate strings of a string field in a PostgreSQL 'group by' query?

对于其他SQL系统,这个想法应该基本相同。您必须搜索正确的聚合函数,其他所有内容都可以使用简单的group by指令完成。

干杯 蒂洛

答案 1 :(得分:0)

很有可能使用for xml path语句在本机tsql中使用详细here

要通过linq访问它,请在db上创建一个存储过程,将其拖到dbml文件中,然后像数据方法一样从数据上下文中调用它。

sp的代码看起来像这样

select
    u.userid,
    substring(( select ',' + cast(p.productid as nvarchar(20))
        from
            user2product up inner join
            product p on up.productid = p.productid
        where
            up.userid = u.userid
        for xml path('')),2,2000000) as Products
from
    users u