How to return 1 single row data from 2 different tables with dynamic contents in sql

◇◆丶佛笑我妖孽 提交于 2019-12-20 05:55:46

问题


Can someone provide answer to this situation?? Suppose I have 2 tables:

Table Books with values Batch_no and Title

Batch_no - Title
1 - A
2 - B

and;

Table Book_Authors with values Batch_no and Author_no

Batch_no - Author_no
1 - 1
1 - 2
1 - 3
2 - 1

How should I merge the values into 1 row which should look like this

Batch_no Author
1 - 1, 2, 3
2 - 1

Any help will be greatly appreciated...Many Thanks!


回答1:


If you take a look here: http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/

there are several techniques you can do this.

Adapting for your situation, here is one that looks simple:

    select batch_no, LEFT(booksauthors, len(booksauthors)-1) as Authors from 
(SELECT ba.Batch_no,

      ( SELECT cast(ba1.Author_no as varchar(10)) + ','

           FROM Book_Authors ba1

          WHERE ba1.Batch_no = ba.Batch_no

          ORDER BY Author_no

            FOR XML PATH('') ) AS BooksAuthors

      FROM Book_Authors ba

      GROUP BY Batch_no )A;


来源:https://stackoverflow.com/questions/5124831/how-to-return-1-single-row-data-from-2-different-tables-with-dynamic-contents-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!