SQL queries contain complex joins, subqueries, and some aggregates
2016-06-28 10:39
471 查看
In the following section we will see an example of an advanced query:
Where we get the,
Department's names with all the students for each department
Students name separated with comma and
Showing the department having at least three students in it
We added a JOIN clause to get the DepartmentName from the Departments table. After that we added a GROUP BY clause with two aggregate functions:
"COUNT" to count the students for each department group.
GROUP_CONCAT to concatenate students for each group with comma separated in one string.
After the GROUP BY, we used the HAVING clause to filter the departments and select only those departments that have at least 3 students.
The result will be as following:
Where we get the,
Department's names with all the students for each department
Students name separated with comma and
Showing the department having at least three students in it
SELECT d.DepartmentName, COUNT(s.StudentId) StudentsCount, GROUP_CONCAT(StudentName) AS Students FROM Departments AS d INNER JOIN Students AS s ON s.DepartmentId = d.DepartmentId GROUP BY d.DepartmentName HAVING COUNT(s.StudentId) >= 3;
We added a JOIN clause to get the DepartmentName from the Departments table. After that we added a GROUP BY clause with two aggregate functions:
"COUNT" to count the students for each department group.
GROUP_CONCAT to concatenate students for each group with comma separated in one string.
After the GROUP BY, we used the HAVING clause to filter the departments and select only those departments that have at least 3 students.
The result will be as following:
sqlite> SELECT ...> d.DepartmentName, ...> COUNT(s.StudentId) StudentsCount, ...> GROUP_CONCAT(StudentName) AS Students ...> FROM Departments AS d ...> INNER JOIN Students AS s ON s.DepartmentId = d.DepartmentId ...> GROUP BY d.DepartmentName ...> HAVING COUNT(s.StudentId) >= 3; DepartmentName StudentsCount Students -------------- ------------- ----------------- IT 3 Michael,John,Jack Physics 3 Sara,Sally,Nancy
相关文章推荐
- 303. Range Sum Query - Immutable
- iOS中UIButton的setImage方法和setBackgroundImage方法区别
- 新建drools项目后报 value '1.8' is not a valid language level错误
- (rwbuilder.conf) 14374587 Post Patch Instructions Would Get Overridden By Autoconfig
- UESTC 92 Journey(LCA)
- UI组件
- UIResponder学习
- UITouch 触摸事件处理(实例)
- UESTC 86 Divide (二进制贪心)
- 关于更新Android sdk之后出现This Android SDK requires Android Developer Toolkit version 23.0.0 or above的解决方法
- post和get在request中,有一个body字段的差别
- 巧用UIResponder进行事件传递
- 获取图片指定点的RGBA
- OPatch cannot process overlay patches because of no OUI support
- iOS开发--- UIScrollView属性以及代理大全
- UESTC 84 Binary Operations(算贡献求期望)
- iOS设备UUID的获取方法(不变的唯一值)
- 项目打包文件build.xml
- build.xml配置编译打包过程(转)
- UVa 10935 queue教学