数据库问题SQL
数据库中存在:
BName Aname flag
X NULL 001
Y NULL 001
M NULL 001
NULL N 001
NULL L 001
A NULL 002
B NULL 003
NULL B 003
实现效果
BName Aname flag
X,Y,M N,L 001
A '' 002
B B 003
在SQL 中如何实现,求大神们指教,谢谢啦。
[解决办法]
CREATE TABLE tb(BName SYSNAME NULL,Aname SYSNAME NULL,flag SYSNAME NULL)
GO
INSERT INTO tb VALUES('X',NULL,'001')
INSERT INTO tb VALUES('Y',NULL,'001')
INSERT INTO tb VALUES('M',NULL,'001')
INSERT INTO tb VALUES(NULL,'N','001')
INSERT INTO tb VALUES(NULL,'L','001')
INSERT INTO tb VALUES('A',NULL,'002')
INSERT INTO tb VALUES('B',NULL,'003')
INSERT INTO tb VALUES(NULL,'B','003')
SELECT flag,
bname = STUFF((SELECT ',' + bname FROM tb a WHERE a.flag = tb.flag FOR XML PATH('')),1,1,''),
aname = STUFF((SELECT ',' + aname FROM tb a WHERE a.flag = tb.flag FOR XML PATH('')),1,1,'')
FROM tb GROUP BY flag