[英]SQL Query - Get the count from many tables
我有一個雇員表,從屬表
員工表
依賴的
現在,我想查詢以獲取雇員總數,處於每個狀態(工作,已退休..)的雇員總數,所有雇員的所有受撫養人數目
有什么幫助嗎?
您要查找的關鍵字是"Count"
例如: 'SELECT COUNT(empid) FROM employee WHERE status = working'
這將為您提供狀態為“工作”的員工人數
這將為您提供按狀態分組的計數
SELECT COUNT(emp.empid) as counts, status
FROM employee emp join employee2 emp2 on emp.empid = emp2.empid
group by status
您可以嘗試使用“ Prepared Statements
:
set @sql = (
select group_concat(distinct
concat(
"sum(case when `status`='", e.status, "' then 1 end) as `", e.status, "`"
)
)
from employee e
);
set @sql = concat("select count(e.empid) total_emp, (select count(*) from dependent) total_dep , ", @sql, " from employee e");
prepare stmt from @sql;
execute stmt;
第一部分將為每個員工狀態動態生成列,並通過子選擇可以計算家屬總數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.