T-SQL 问题
RT 这是源表dbo.abc
iddbnameaccount
1db-1sa
2db-1cn\A
3db-1cn\B
4db-2sa
5db-2cn\C
6db-3cn\D
7db-3cn\E
8db-4admin
我的代码及其想要的结果:
SELECT t3.dbname_1 AS 数据库名,MAX(ISNULL(t3.account_1,'')+';'+ISNULL(t3.account_2,'')+';'+ISNULL(t4.account,'')) AS 对应账号FROM (SELECT t1.id AS id_1,t1.dbname AS dbname_1,t1.account AS account_1,t2.id AS id_2,t2.dbname AS dbname_2,t2.account AS account_2 FROM dbo.abc t1LEFT JOIN dbo.abc t2ON t1.dbname=t2.dbname AND t1.account<>t2.account) t3LEFT JOIN dbo.abc t4ON t3.dbname_1=t4.dbname AND t3.account_1<>t4.account AND t3.account_2<>t4.accountGROUP BY t3.dbname_1
select dbname as [数据库名], [对应账号]=stuff((select ';'+account from abc where dbname=a.dbname for xml path('')),1,1,'')from abc agroup by id