【发布时间】:2019-07-03 17:59:16
【问题描述】:
请帮忙,我开始学习 sql,我必须将所有 3 位作者组合在一行中。
如何删除 dups 并只显示一个结果?
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
【问题讨论】:
-
非图片请分享文本样本数据和预期输出
-
共享。请帮帮我,谢谢!
-
你的预期结果是什么
-
对于给您带来的不便,我深表歉意。我添加了所需的结果
-
“如何删除 dups”呢?我没有在结果集中看到重复项。
标签: sql-server union common-table-expression union-all