日期:2014-05-17  浏览次数:20590 次

问一个常用sql语句,先谢了.
本帖最后由 a291410855 于 2013-07-19 15:54:39 编辑
主表,
1   name1
2   name2,
子表,
1   1   d1
2   1   d2
3   2   d3,
4   2   d4
如何得到
1  name1 d1,d2
2  name2 d3,d4

主表的第一列与子表的第二列关联.

------解决方案--------------------

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 (