日期:2014-05-17 浏览次数:20704 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-11-05 10:18:38
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([ID] varchar(3),[NAME] varchar(5))
insert [huang]
select '001','NAME1' union all
select '002','NAME2' union all
select '003','NAME1' union all
select '004','NAME2' union all
select '005','NAME2' union all
select '006','NAME1'
--------------开始查询--------------------------
select a.NAME,
stuff((select ','+CONVERT(VARCHAR(100),CONVERT(INT,[ID])) from [huang] b
where b.NAME=a.NAME
for xml path('')),1,1,'') 'ID'
from [huang] a
group by a.NAME
----------------结果----------------------------
/*
NAME ID
----- -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------