日期:2014-05-16 浏览次数:20458 次
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2014-04-18 19:43:50
-- Version:
-- Microsoft SQL Server 2008 (SP3) - 10.0.5500.0 (Intel X86)
-- Sep 22 2011 00:28:06
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[a]
if object_id('[a]') is not null drop table [a]
go
create table [a]([tid] int,[a] sql_variant,[b] sql_variant)
insert [a]
select 1,null,null union all
select 2,null,null union all
select 3,null,null
--> 测试数据:[b]
if object_id('[b]') is not null drop table [b]
go
create table [b]([tid] int,[person] varchar(4),[type] varchar(4))
insert [b]
select 1,'王二','工人' union all
select 1,'张三','工人' union all
select 1,'李四','领导' union all
select 1,'王五','工人' union all
select 2,'..','..' union all
select 2,'..','..'
--------------开始查询--------------------------
select
b.tid,
max(case when b.type='领导' then person else '' end) as a,
(
SELECT [person] + ','
FROM b as t
WHERE tid = b.tid and t.type<>'领导' for XML PATH('')
) as b
from b
group by
b.tid
----------------结果----------------------------
/* tid &n