日期:2014-05-17 浏览次数:20627 次
with tb (a,b) as(
select 1,'name1' union
select 2,'name2'
),tc(a,b)as(
select 1,'d1' union
select 1,'d2' union
select 2,'d3' union
select 2,'d4'
)
select distinct *,
stuff((select ','+b from tc where tb.a=tc.a for xml path('')),1,1,'') from tb
----------------------------
-- Author :DBA_Huanzj(發糞塗牆)
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3000.0 (X64)
-- Oct 19 2012 13:38:57
-- Copyright (c) Microsoft Corporation
-- Enterprise Evaluation Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go
create table [A]([id] int,[name] varchar(5))
insert [A]
select 1,'name1' union all
select 2,'name2'
--> 测试数据:[B]
if object_id('[B]') is not null drop table [B]
go
create table [B]([id] int,[aid] int,[bname] varchar(3))
insert [B]
select 1,1,'d1' union all
select 2,1,'d2' union all
select 3,2,'d3' union all
select 4,2,'d4'
--------------开始查询--------------------------
select a.id,a.name,b.bname from [A] a inner join (