A表和B表是一對多關系,要如何寫sql語句實現圖中的效果。
SQLServer如下
CREATE TABLE A(
id int,
name varchar(20)
);
CREATE TABLE B(
bid int,
name varchar(20),
pid int
);
insert into A(id,name) VALUES(1,'張三');
insert into A(id,name) VALUES(2,'李四');
insert into B(bid,name,PID) VALUES(1,'王五',1);
insert into B(bid,name,PID) VALUES(2,'張飛',1);
insert into B(bid,name,PID) VALUES(3,'錢六',2);
select a.*,r.data from a left join(
SELECT pid, data=STUFF((SELECT ','+name FROM b t WHERE pid=t1.pid FOR XML PATH('')), 1, 1, '')
FROM b t1
GROUP BY pid
) r on a.id=r.pid