SQL queries contain complex joins, subqueries, and some aggregates

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值