日期:2014-05-19  浏览次数:20456 次

一条SQL,请帮忙
CREATE   TABLE   #A(A   INT,B   INT)
INSERT   INTO   #A   SELECT   1,2  
CREATE   TABLE   #A(A   INT,B   INT)
INSERT   INTO   #A   SELECT   1,3  
INSERT   INTO   #A   SELECT   2,4  
INSERT   INTO   #A   SELECT   2,5  
INSERT   INTO   #A   SELECT   3,6  
INSERT   INTO   #A   SELECT   3,7  

SELECT   *   FROM   #A   T1  

如何用一条SQL出以下结果
A     B
1   2,3
2   4,5
3   6,7
谢谢

------解决方案--------------------
CREATE TABLE #A(A INT,B INT)
INSERT INTO #A SELECT 1,2
INSERT INTO #A SELECT 1,3
INSERT INTO #A SELECT 2,4
INSERT INTO #A SELECT 2,5
INSERT INTO #A SELECT 3,6
INSERT INTO #A SELECT 3,7
go
SELECT *
FROM(
SELECT DISTINCT
A
FROM #A
)A
OUTER APPLY(
SELECT
[values]=STUFF(REPLACE(REPLACE(
(
SELECT B FROM #A N
WHERE A= A.A
FOR XML AUTO
), ' <N B= " ', ', '), ' "/> ', ' '), 1, 1, ' ')
)N

/*
A values
----------- ---------
1 2,3
2 4,5
3 6,7

*/
Drop table #a