日期:2014-05-17 浏览次数:20452 次
create table #emp
(empid varchar(10),
empname varchar(20)
)
create table #dept
(deptid varchar(10),
deptname varchar(20)
)
create table #EDRelation
(empid varchar(10),
deptid varchar(10)
)
insert into #emp values('001','aa')
insert into #emp values('002','bb')
insert into #emp values('003','cc')
insert into #emp values('004','dd')
insert into #emp values('005','EE')
insert into #emp values('006','FF')
insert into #dept values('IT1','it')
insert into #dept values('AC1','ac')
insert into #dept values('CW1','CW')
insert into #EDRelation values('001','IT1')
insert into #EDRelation values('002','IT1')
insert into #EDRelation values('003','AC1')
insert into #EDRelation values('004','CW1')
insert into #EDRelation values('005','CW1')
insert into #EDRelation values('006','IT1')
IF OBJECT_ID('TEMPDB..#DUAL') IS NOT NULL
DROP TABLE #DUAL
select * ,'员工'+编号 as 员工编号
into #dual
from (
SELECT convert(varchar(10),ROW_NUMBER() OVER(PARTITION BY #DEPT.DEPTID ORDER BY #EMP.EMPID ))AS 编号,
#emp.*,#dept.*from #emp,#dept, #EDRelation
where #emp.empid=#EDRelation.empid
and #dept.deptid=#EDRelation.deptid)a
declare @sql varchar(8000)
set @sql = 'select deptname '
select @sql = @sql + ' , max(case 编号 when ''' + 编号 + ''' then empname else '''' end) '''+员工编号+''''
from (select distinct 编号,员工编号 from #dual) as a
set @sql = @sql + ' from #dual group by deptname'
exec(@sql)