3

我有来自成员系统中两个表的数据,如下所示:

Table: listuser
userid  listid
===========
1       5
1       8
1       3
2       5
2       3
3       4
4       4
5       3
6       4

Table: list
id  name
==============
3   Members
4   Non Members
5   Subscribers
8   Test

我想要达到的结果如下:

userid  lists
===================
1       Members, Subscribers, Test,
2       Members, Subscribers
3       Non Members,
4       Non Members,
5       Members,
6       Non Members,

用户可以属于 0 到 n 个列表。我尝试了多种方法,但总是以多行用户标识结束,这是我试图消除的。我会很高兴得到一些帮助。

4

1 回答 1

3

尝试这个。它会帮助你

SELECT DISTINCT lu2.userid,(
SELECT ISNULL(l1.name, '') + ', '
FROM dbo.listuser lu1 JOIN dbo.list l1 ON lu1.listid = l1.id
WHERE lu1.userid = lu2.userid 
FOR XML PATH('')) AS name
FROM dbo.listuser lu2
ORDER BY lu2.userid

SQL Fiddle示例

于 2012-10-21T13:58:05.790 回答