日期:2014-05-16 浏览次数:20581 次
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2014-04-08 10:53:26
-- Verstion:
-- Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
-- Jul 9 2008 14:43:34
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([行业] varchar(50),[企业名] varchar(50))
insert [tb]
select '行业1','企业1' union all
select '行业1','企业2' union all
select '行业2','企业2' union all
select '行业2','企业3'
--------------开始查询--------------------------
select 企业名, [行业]=stuff((select ','+[行业] from tb t where 企业名=tb.企业名 for xml path('')), 1, 1, '')
from tb
group by 企业名
----------------结果----------------------------
/* 企业名 行业
-------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
企业1 行业1
企业2 行业1,行业2
企业3