微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在SQL Server一栏中获得所有课程

如何解决在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      |
+-----+----------+------------+

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

+-----+-- |
|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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。