【问题标题】:SQL Server combine rows and columnsSQL Server 组合行和列
【发布时间】: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


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多