查询语句请教,高手进。。。。。。。。。。。
员工表:
员工号,员工姓名
部门表:
部门号,部门名称
员工、部门关联表:
部门号,员工号
如果我想新建一个视图,显示如下信息:
部门名称 员工1 员工2 员工3
那么该视图的select语句应该如何写啊?
select
[解决办法]
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)
select '九两'
insert into dept_employee(deptno,empno)
select 1 ,1 union
select 1,2 union
select 1,3 union
select 2,4 union
select 3 ,5
select * from dept
select * from employee
select * from dept_employee
select dname,ename,ROW_NUMBER() over(partition by dname order by ename) as empno
from dept d,employee e ,dept_employee de
where d.deptno=de.deptno
and e.empno=de.empno
--效果1:
--工程部八斤,九两,李四
--销售部王五
--研发部张三
select dname,ename,ROW_NUMBER() over(partition by dname order by ename) as empno
into #test
from dept d,employee e ,dept_employee de
where d.deptno=de.deptno
and e.empno=de.empno
select dname,left(ename,len(ename)-1)
from(
select dname,(select ename+',' from #test t1 where t1.dname=t.dname for xml path ('')) as ename
from #test t
group by dname)t2
drop table #test
go
--效果2:
--工程部八斤九两李四
--销售部王五
--研发部张三
select dname,ename,ROW_NUMBER() over(partition by dname order by ename) as bh
into #test
from dept d,employee e ,dept_employee de
where d.deptno=de.deptno
and e.empno=de.empno
declare @sql nvarchar(1024);
set @sql = 'select dname '
select @sql = @sql + ' , max(case bh when ''' +CAST(bh as varchar(10))+ ''' then ename else '''' end) '''+'employee'+CAST(bh as varchar(10))+''''
from (select distinct bh from #test) t
set @sql = @sql + ' from #test group by dname'
print @sql
exec(@sql)
drop table #test
go