日期:2014-05-18  浏览次数:20495 次

T-SQL 问题
RT 这是源表dbo.abc
id dbname account
1 db-1 sa
2 db-1 cn\A
3 db-1 cn\B
4 db-2 sa
5 db-2 cn\C
6 db-3 cn\D
7 db-3 cn\E
8 db-4 admin

我的代码及其想要的结果:
SQL code

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 t1
LEFT JOIN dbo.abc t2
ON t1.dbname=t2.dbname AND t1.account<>t2.account) t3
LEFT JOIN dbo.abc t4
ON t3.dbname_1=t4.dbname AND t3.account_1<>t4.account AND t3.account_2<>t4.account
GROUP BY t3.dbname_1



结果:
数据库名 对应账号
db-1 sa;cn\B;cn\A
db-2 sa;cn\C;
db-3 cn\E;cn\D;
db-4 admin;;

=========================分割线================
显然我的代码没有扩展性。但我想不出好的方法来实现这个功能了。而且我想用一段t-sql,而不用存储过程或者函数(可以过程实现)实现。

有高手请教一下吗?

------解决方案--------------------
SQL code

select dbname as  [数据库名],
 [对应账号]=stuff((select ';'+account from abc where dbname=a.dbname for xml path('')),1,1,'')
from abc a
group by id