请帮忙,我开始学习sql,我必须将所有3位作者合为一行。
我怎样才能删除公仔,只显示一个结果?
with cte_authors (titleID, Authors, lvl)
as
(select distinct titles.title_id, convert(nvarchar(max), au_fname + ' ' + au_lname) as Authors , 1 as lvl
from titles inner join
titleauthor on titles.title_id = titleauthor.title_id inner join
authors on titleauthor.au_id = authors.au_id
where au_ord > 2
union all
select titleauthor.title_id, Authors + '\' + au_fname + ' ' + au_lname , lvl + 1
from titleauthor inner join
cte_authors on cte_authors.titleID = titleauthor.title_id inner join
titles on titles.title_id = cte_authors.titleID inner join
authors on authors.au_id = titleauthor.au_id
where lvl< 3)
Select * from cte_authors
group by titleID, Authors, lvl
order by lvl
结果:
titleID Authors lvl
TC7777 Burt Gringlesby 1
TC7777 Burt Gringlesby\Akiko Yokomoto 2
TC7777 Burt Gringlesby\Burt Gringlesby 2
TC7777 Burt Gringlesby\Michael O'Leary 2
TC7777 Burt Gringlesby\Akiko Yokomoto\Akiko Yokomoto 3
TC7777 Burt Gringlesby\Akiko Yokomoto\Burt Gringlesby 3
TC7777 Burt Gringlesby\Akiko Yokomoto\Michael O'Leary 3
TC7777 Burt Gringlesby\Burt Gringlesby\Akiko Yokomoto 3
TC7777 Burt Gringlesby\Burt Gringlesby\Burt Gringlesby 3
TC7777 Burt Gringlesby\Burt Gringlesby\Michael O'Leary 3
TC7777 Burt Gringlesby\Michael O'Leary\Akiko Yokomoto 3
TC7777 Burt Gringlesby\Michael O'Leary\Burt Gringlesby 3
TC7777 Burt Gringlesby\Michael O'Leary\Michael O'Leary 3
我需要的结果:
titleID Authors lvl
TC7777 Burt Gringlesby\Michael O'Leary\Akiko Yokomoto 3
答案 0 :(得分:1)
如果只需要一行包含所有作者的串联字符串,则不需要CTE。
SELECT titles.title_id,
STUFF((
SELECT '\' + a.au_fname + ' ' + a.au_lname
FROM dbo.titleauthor ta
INNER JOIN dbo.authors a ON a.au_id = ta.au_id
WHERE ta.title_id = titles.title_id
ORDER BY ta.au_ord DESC
FOR XML PATH('')
), 1, 1, '') AS Authors,
(SELECT MAX(au_ord) FROM dbo.titleauthor WHERE title_id = titles.title_id) lvl
FROM titles
返回:
title_id Authors lvl
TC7777 Burt Gringlesby\Michael O'Leary\Akiko Yokomoto 3