34,838
社区成员




create table bt(bookNo varchar(10),TeacherNo varchar(10))
insert bt select 'b001','t004'
union all select 'b002','t001'
union all select 'b002','t002'
union all select 'b002','t003'
create table tc(teacherNo varchar(10),teacherName varchar(10),department varchar(10))
insert tc select 't001' , '张三', '管理系'
union all select 't002', '李四' , '计算机系'
union all select 't003', '王五' , '计算机系'
union all select 't004', '测试员', '测控系'
go
create function dbo.getmess(@book varchar(10),@depart varchar(10),@m int)
returns varchar(20)
as
begin
declare @s varchar(20)
declare @t table(id int identity,bookno varchar(10),teacherno varchar(10),teachername varchar(10),department varchar(10))
insert @t select bookno,teacherno,'','' from bt where @book = bookno
update a set teachername = b.teachername,department = b.department from @t a,tc b where a.teacherno = b.teacherno
if @m = 2 select @s =rtrim(min(id)) from @t where department = @depart
if @m = 1 select @s = teachername from @t where id = (select min(id) from @t where department = @depart)
if @m = 0 select @s=isnull(@s+',','')+teachername from @t order by id
return @s
end
go
declare @dd varchar(10)
set @dd = '计算机系'
select bookno,dbo.getmess(bookno,@dd,0) 全部作者,dbo.getmess(bookno,@dd,1) 最前作者,dbo.getmess(bookno,@dd,2) 最前名次 from bt a
where exists(select 1 from tc where teacherno = a.teacherno and department = @dd)
group by bookno
go
drop table bt,tc
drop function getmess
/*
bookno 全部作者 最前作者 最前名次
---------- -------------------- -------------------- --------------------
b002 张三,李四,王五 李四 2
*/