表结构如下:
A表:
B表
B表TaskId作为外键关联A表TaskId
想要实现如下查询结果:
请教大神这个应该怎么查询,有什么参考没?
select S.taskid,S.taskcode,LEFT(S.username,LEN(S.username)-1) from (
select A.taskid,A.taskcode,
(select B.username+',' from B where B.taskid=A.taskid for xml path('')) username
from A
group by A.taskid,A.taskcode
) S
select TaskId,TaskCode,wm_connect(UserName) over (partion by TaskID) from A ,B where A.TaskID= B.TaskID;
,主要查询 sql 的统计类的相关函数。
wm_connect和partion查询语句报有语法错误
百度 FOR XML PATH
WITH -- 造数
A AS
(
SELECT TaskId ,TaskCode,UserName FROM (
SELECT 'BB1' as TaskCode ,1 as TaskId ,'李克勤' as UserName union
SELECT 'BB2',2,'黎明' union
SELECT 'BB3',2,'刘德华' union
SELECT 'BB4',2,'王杰' ) A
)
-- TaskId, UserName
SELECT TaskId,
(SELECT UserName+','
FROM A
FOR XML PATH ('')) AS UserList
FROM A
GROUP BY TaskId