获取一栏SQL服务器所有课程、章节

Get all course, chapter in one column SQL Server

课程

+-----+----------+
| id  | c_name   |
+-----+----------+
| 1   | course1  |
| 7   | course2  |
+-----+----------+

章节

+-----+----------+------------+
| id  |  Ch_name | c_id       |
+-----+----------+------------+
| 3   | Chapter1 |     1      |
| 9   | Chapter2 |     7      |
| 11  | Chapter3 |     1      |
| 17  | Chapter4 |     1      |
+-----+----------+------------+

我正在尝试 select 所有数据,以便生成以下输出:

+-----+-- |
|Course   |
+-----+-- |
|Course1  |
|Chapter1 |
|Chapter3 | 
|Chapter4 |
|         |
|Course2  |
|Chapter2 |

我试过这样:

select
    c.CourseID ,
    'Course' as table_name,
    c.CourseName as Course,
    '' as Chapter        
from [MstCourse]c
union 
select
    s.CourseID,
    'Chapter' as table_name,
    c.CourseName as Course,
    s.ChapterName as Chapter       
from [MstCourse] c
inner JOIN [ManageChapter] s ON c.CourseID= s.CourseID    
order by Course, Chapter

但我没有在单列中得到结果。

您可以使用 group by ... with rollup 子句实现此目的。

示例数据

create table course
(
  id int,
  name nvarchar(10)
);
insert into course(id, name) values
(1, 'Course1'),
(7, 'Course2');

create table chapter
(
  id int,
  name nvarchar(10),
  c_id int
);
insert into chapter(id, name, c_id) values
(3 , 'Chapter1', 1),
(9 , 'Chapter2', 7),
(11, 'Chapter3', 1),
(17, 'Chapter4', 1);

解决方案

select coalesce(ch.Name, co.Name) as [Course]
from course co
join chapter ch
  on ch.c_id = co.id
group by co.Name, ch.Name with rollup
having grouping(co.Name) <> 1
order by co.Name, ch.Name;

有关此解决方案工作原理的一些背景信息,请查看 this fiddle