使用 CASE 创建一个新列并可能计数
现在,我有一个查询可以获取 3 列。
选择 a.studentID、a.classdetailID、c.course_title
来自学生课程详细信息a,班级详细信息b,课程c
WHERE b.classdetailID = a.classdetailID
和 b.courseID = c.courseID
排序依据 c.course_title、b.classdetailID
我得到的是一列,显示完成该课程的学生的 ID、他们所在班级的 ID 以及课程本身的标题。沿着这些思路:
5---8----Airline Security Operations
4---8----Airline Security Operations
6---8----Airline Security Operations
4---9----Airline Security Operations
8---10---Airline Security Operations
5---10---Airline Security Operations
1---1----Airport Design and Construction
4---1----Airport Design and Construction
2---1----Airport Design and Construction
1---2----Airport Design and Construction
我需要的是一个向我展示类似这样的内容的表格:
course_title Number of Classes Number of students
Airline Security Operations 3 4
我想过使用CASE
,但当我想到它时,我就迷失了。我很感激你的帮助。
答案,感谢 gbn:
SELECT c.course_title, COUNT( DISTINCT a.studentID ) AS“课程中的学生”, COUNT(DISTINCT a.classdetailID ) AS“课程总数”
来自学生课程详情
加入 classdetails b ON b.classdetailID = a.classdetailID
加入课程 c ON b.courseID = c.courseID
小组,作者:c.course_title
Right now, I have a query that gets me 3 columns.
SELECT a.studentID, a.classdetailID, c.course_title
FROM studentcoursedetails a, classdetails b, course c
WHERE b.classdetailID = a.classdetailID
AND b.courseID = c.courseID
ORDER BY c.course_title, b.classdetailID
What I get is a column that shows the ID of the student that did the course, the ID of the class they were in and the title of the course itself. Something along these lines:
5---8----Airline Security Operations
4---8----Airline Security Operations
6---8----Airline Security Operations
4---9----Airline Security Operations
8---10---Airline Security Operations
5---10---Airline Security Operations
1---1----Airport Design and Construction
4---1----Airport Design and Construction
2---1----Airport Design and Construction
1---2----Airport Design and Construction
What I need is a table that shows me something like this:
course_title Number of Classes Number of students
Airline Security Operations 3 4
I thought of using CASE
, but when I think about it, I just get lost. I'd appreciate your help.
The answer, thanks to gbn:
SELECT c.course_title, COUNT( DISTINCT a.studentID ) AS "Students in Course" , COUNT( DISTINCT a.classdetailID ) AS "Total Classes"
FROM studentcoursedetails a
JOIN classdetails b ON b.classdetailID = a.classdetailID
JOIN course c ON b.courseID = c.courseID
GROUP BY c.course_title
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您希望
使用正确的 JOIN 语法对每个
course_title
的每个不同出现进行计数(使用 SQL Server 列别名语法)You want to count each distinct occurence per
course_title
Like this (with SQL Server column alias syntax) with proper JOIN syntax