日期:2014-05-16 浏览次数:20800 次
DECLARE @hooyes TABLE
(
area_name VARCHAR(50) ,
area_code VARCHAR(20)
)
INSERT INTO @hooyes
( area_code, area_name )
VALUES ( '1001', 'CA' )
INSERT INTO @hooyes
( area_code, area_name )
VALUES ( '1002', 'CA' )
INSERT INTO @hooyes
( area_code, area_name )
VALUES ( '1003', 'CA' )
INSERT INTO @hooyes
( area_code, area_name )
VALUES ( '2001', 'US' )
INSERT INTO @hooyes
( area_code, area_name )
VALUES ( '4001', 'AU' )
INSERT INTO @hooyes
( area_code, area_name )
VALUES ( '4002', 'AU' )
SELECT area_name ,
area_code
FROM @hooyes
/*
直接查询的结果:
area_name area_code
CA 1001
CA 1002
CA 1003
US 2001
AU 4001
AU 4002
*/
/*
想要一条 SQl 查出如下结果,按area_name分组,并且合并 area_code,以逗号隔开。
area_name area_code
CA 1001,1002,1003
US 2001
AU 4001,4002
*/
SELECT area_name ,
STUFF((SELECT ',' + b.area_code FROM @hooyes AS b WHERE b.area_name = a.area_name FOR XML PATH('') ) ,1,1,'')
FROM @hooyes AS a
GROUP BY area_name
--
area_name
-------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
AU 4001,4002
CA &nbs