日期:2014-05-16 浏览次数:20778 次
WITH a1 (团队,小组,员工) AS
(
select 'a','A','张三' UNION ALL
select 'b','C','张三' UNION ALL
select 'c','E','张三' UNION ALL
select 'd','G','张三' UNION ALL
select 'e','H','张三'
)
,a2 (团队,小组,员工) AS
(
select 'e','B','李四' UNION ALL
select 'f','C','李四' UNION ALL
select 'g','D','李四'
)
,a3 (团队,小组,员工) AS
(
select 'a','A','王五' UNION ALL
select 'c','E','王五' UNION ALL
select 'e','B','王五' UNION ALL
select 'h','D','王五'
)
SELECT * INTO #cu FROM a1
UNION
SELECT * FROM a2
UNION
SELECT * FROM a3
declare @sql varchar(max),@col varchar(max)
SET @sql=''
select @sql = @sql + ','+quotename(员工) from (SELECT DISTINCT 员工 FROM #cu) a
SElecT @col='[团队],[小组]'+REPLACE(REPLACE(@sql,'[','isnull(['),']','],'''')')
set @sql = STUFF(@sql,1,1,'')
set @sql = 'select '+@col+' from #cu a pivot (max(员工) for 员工 in (' + @sql + ')) b order by 1,2'
--PRINT @sql
exec (@sql)
create table t1(团队 varchar(10),小组 varchar(10),员工 varchar(10))
insert into t1
select 'a', 'A', '张三' union all
select 'b', 'C', '张三' union all
select 'c', 'E', '张三' union all
select 'd', 'G', '张三' union all
select 'e', 'H', '张三'
create table t2(团队 varchar(10),小组 varchar(10),员工 varchar(10))
insert into t2
select 'e', 'B', '李四' union all
select 'f', 'C', '李四' union all
select 'g', 'D', '李四'
create table t3(团队 varchar(10),小组 varchar(10),员工 varchar(10))
insert into t3
select 'a', 'A', '王五' union all
select 'c', 'E', '王五' union all
select 'e', 'B', '王五' union all
select 'h', 'D', '王五'
go
select t.团队,t.小组,t1.员工,t2.员工,t3.员工
from
(
select 团队,小组 from t1 union
select 团队,小组 from t2 union
select 团队,小组 from t3
)t
left join t1 on t1.团队 = t.团队 and t1.小组 = t.小组
left join t2 on t2.团队 = t.团队 and t2.小组 = t.小组
left join t3 on t3.团队 = t.团队 and t3.小组 = t.小组
/*
团队 小组 员工 员工 员工
a A 张三 NULL 王五
b C 张三 NULL NULL
c E 张三 NULL 王五
d G 张三 NULL NULL
e B NULL 李四 王五
e H 张三 NULL NULL
f C NULL 李四 NULL