You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何查询授课超2门的教职工及编写授课超1门的SQL查询语句?

SQL Queries for Staff Teaching Multiple Units

Let's break down both questions using your provided database schema. First, a quick reminder that we'll be working primarily with the Staff table (for staff details) and Taught_by table (which tracks which staff teach which units).


1. Find Staff Who Teach More Than 2 Units

To get staff who teach over 2 distinct units, we need to group staff by their ID, count how many unique units they're assigned to, then filter for those with a count greater than 2. We'll also join with the Staff table to pull in their name and other details instead of just an ID.

Here's the query:

SELECT s.Staff_id, s.StaffName, s.Position, s.Gender
FROM Staff s
JOIN Taught_by tb ON s.Staff_id = tb.Staff_id
GROUP BY s.Staff_id, s.StaffName, s.Position, s.Gender
HAVING COUNT(DISTINCT tb.Unit_code) > 2;

Notes:

  • COUNT(DISTINCT tb.Unit_code) ensures we count unique units (in case a staff member teaches the same unit on multiple weekdays, we don't double-count it).
  • The GROUP BY includes all non-aggregated columns from the Staff table (this is required in most SQL dialects like PostgreSQL, MySQL with strict mode, etc.).

2. SQL Query to Show Staff Who Teach More Than 1 Unit

This is almost identical to the first query—we just adjust the count threshold to greater than 1. Again, we'll join with Staff to get full staff details:

SELECT s.Staff_id, s.StaffName, s.Position, s.Gender
FROM Staff s
JOIN Taught_by tb ON s.Staff_id = tb.Staff_id
GROUP BY s.Staff_id, s.StaffName, s.Position, s.Gender
HAVING COUNT(DISTINCT tb.Unit_code) > 1;

Optional: If you only need Staff IDs

If you don't need the full staff details, you can simplify the query to:

SELECT Staff_id
FROM Taught_by
GROUP BY Staff_id
HAVING COUNT(DISTINCT Unit_code) > 1;

内容的提问来源于stack exchange,提问作者tomahawk793

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 13:52:29