请教大家一个SQL语句

qxm 2003-07-02 04:00:28
两个表,
book(id,name,press)
book_chd(id,aid,aname,position)
book_chd是book的从表,aid,aname,position分别表示书的作者ID,作者名字和作者的排名。
如book有一条记录(1,'数据库原理','机械工业出版社')
book_chd有三条记录(1,1,'aaa',2), (1,2,'bbb',1), (1,3,'ccc',3),
分别表示书'数据库原理'(序号为1)的作者为'aaa'(作者ID为1)、'bbb'(作者ID为2)、'ccc'作者ID为3),排名分别为2、1、3。
现在要求的报表结果是:id,name,press,author,
其中author是三位作者按照作者排名顺序连接成一个字符串。这里的结果应该为
id name press author
1 '数据库原理' '机械工业出版社' 'bbb aaa ccc'

请问大家这个SQL该怎么写?
...全文
28 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
CrazyFor 2003-07-02
  • 打赏
  • 举报
回复
1,建自定义函数
CREATE FUNCTION dbo.uf_xd (@parm int)
RETURNS Nvarchar(4000) AS
BEGIN
declare @return Nvarchar(4000)
select @return=isnull(@return,N'' +isnull(aname,N''))+N' ' from book_chd where id=@parm order by position
return (@return)
END

go


2,
select id , name ,press,uf_xd(id) as author from book_chd
愉快的登山者 2003-07-02
  • 打赏
  • 举报
回复
1,建自定义函数
create function getstr(@id Nchar(4000))
returns Nvarchar(4000)
as
begin
declare @str Nvarchar(2000)
set @str=N''
select @str=@str+rtrim(aname)+N' ' from book_chk
where xh=@id order by position
if @str<>N''
set @str=left(@str,len(@str)-1)
return @str
end

GO

2,
select id,name,press,dbo.getstr(id) as author from book group by id
愉快的登山者 2003-07-02
  • 打赏
  • 举报
回复
1,建自定义函数
create function getstr(@id Nchar(4000))
returns Nvarchar(4000)
as
begin
declare @str Nvarchar(2000)
set @str=N''
select @str=@str+rtrim(xmmc)+N' ' from book_chk
where xh=@id
if @str<>N''
set @str=left(@str,len(@str)-1)
return @str
end

GO

2,
select A.id,A.name,A.press,dbo.getstr(A.id) as author from book group by id
愉快的登山者 2003-07-02
  • 打赏
  • 举报
回复
1,建自定义函数
create function getstr(@id Nchar(4000))
returns Nvarchar(4000)
as
begin
declare @str Nvarchar(2000)
set @str=N''
select @str=@str+rtrim(xmmc)+N' ' from book_chk
where xh=@id
if @str<>N''
set @str=left(@str,len(@str)-1)
return @str
end

GO

2,
select A.id,A.name,A.press,dbo.getstr(A.id) as author from book group by id
dlkfth 2003-07-02
  • 打赏
  • 举报
回复
CREATE FUNCTION dbo.uf_xd (@parm int)
RETURNS varchar(2000) AS
BEGIN



declare @return varchar(2000)

select @return=isnull(@return,'')+' ' +isnull(aname,'') from book_chd where id=@parm order by position




return (@return)
END
select id , name ,press,uf_xd(id) as author from book_chd
dlkfth 2003-07-02
  • 打赏
  • 举报
回复
CREATE FUNCTION dbo.uf_xd (@parm int)
RETURNS varchar(2000) AS
BEGIN



declare @return varchar(2000)

select @return=isnull(@return,'')+' ' +isnull(aname,'') from book_chd where id=@parm order by position




return (@return)
END
select id , name ,press,uf_xd(id) as author from book_chd

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧