问题描述
课程
+-----+----------+
| id | c_name |
+-----+----------+
| 1 | course1 |
| 7 | course2 |
+-----+----------+
章节
+-----+----------+------------+
| id | Ch_name | c_id |
+-----+----------+------------+
| 3 | Chapter1 | 1 |
| 9 | Chapter2 | 7 |
| 11 | Chapter3 | 1 |
| 17 | Chapter4 | 1 |
+-----+----------+------------+
+-----+-- |
|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,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',(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。