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

MySQL跨表统计多列数据:基于员工主表与打卡表的统计需求

Solution for Department & Sub-Department Employee Count with Punch Data Join

Got it, let's break down how to get the stats you need from the employee_master and punching_data_table tables. I'll share two common approaches depending on your desired output format.

Option 1: Row per Sub-Department (with Department Total)

This query returns each sub-department as a separate row, along with the total number of employees in its parent department. It only includes employees who have a punch record—swap INNER JOIN with LEFT JOIN if you need to include employees without punches.

SELECT
    em.dept_id,
    -- Calculate total employees in the department using a window function
    COUNT(DISTINCT em.emp_code) OVER (PARTITION BY em.dept_id) AS dept_count,
    em.sub_dept_id,
    -- Count employees in the specific sub-department
    COUNT(DISTINCT em.emp_code) AS sub_dept_count
FROM
    employee_master em
INNER JOIN
    punching_data_table pd ON em.emp_code = pd.emp_code
GROUP BY
    em.dept_id, em.sub_dept_id
ORDER BY
    em.dept_id, em.sub_dept_id;

Sample Output:

dept_iddept_countsub_dept_idsub_dept_count
104211
104223
112202

Option 2: Row per Department (with Aggregated Sub-Department Counts)

If you prefer a single row per department with all sub-department stats in one field, use GROUP_CONCAT to aggregate the sub-department counts into a readable string:

SELECT
    em.dept_id,
    COUNT(DISTINCT em.emp_code) AS dept_count,
    -- Aggregate sub-department counts into a single formatted string
    GROUP_CONCAT(
        CONCAT('sub_dept_', em.sub_dept_id, ': ', COUNT(DISTINCT em.emp_code))
        SEPARATOR ', '
    ) AS sub_dept_counts
FROM
    employee_master em
INNER JOIN
    punching_data_table pd ON em.emp_code = pd.emp_code
GROUP BY
    em.dept_id
ORDER BY
    em.dept_id;

Sample Output:

dept_iddept_countsub_dept_counts
104sub_dept_21: 1, sub_dept_22: 3
112sub_dept_20: 2

Key Notes

  • Use DISTINCT in COUNT() to avoid duplicate counts if an employee has multiple punch records (your sample data has one per employee, but it's a safe guard for real-world scenarios).
  • Switch to LEFT JOIN instead of INNER JOIN if you need to include employees who didn't punch in—their present value will be NULL, but they'll still be counted in the department/sub-department totals.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:38:37