假设我有这张表:
+-----+------+------------+
| eid | dept | joining |
+-----+------+------------+
| 1 | IT | 1982-01-13 |
| 2 | IT | 1983-01-13 |
| 3 | CSE | 1984-04-13 |
| 4 | CSE | 1983-03-23 |
| 5 | IT | 1985-03-23 |
| 6 | ECE | 1986-03-23 |
| 7 | ECE | 1986-11-23 |
+-----+------+------------+
现在,我希望获得1983年1月1日之后加入的每个部门的员工人数记录。
我尝试了这个查询:
select count(a.eid) as total, dept
from (
select *
from t1
where dept = 'IT'
having DATE(joining) > '1982-01-01'
) as a;
+-------+------+
| total | dept |
+-------+------+
| 3 | IT |
+-------+------+
但我需要一个表中的所有部门。
select joining, dept, count(*)
from t1
group by dept
having(joining) > '1982-01-01'
order by joining;
没有这样的结果。
答案 0 :(得分:2)
您需要一个简单的group by子句,其中包含过滤所需日期的位置,如下所示:
select dept,count(*)
from t1
where joining > '1982-01-01'
group by dept
答案 1 :(得分:1)
having
子句是应用于group by
子句创建的组的条件。您需要使用一个简单的where
子句,它将条件分别应用于每一行:
SELECT dept, COUNT(*)
FROM t1
WHERE joining > '1982- 01-01'
GROUP BY dept
答案 2 :(得分:1)
您是否曾尝试将日期转移到WHERE子句中,而不是将其放在GROUP BY中,如下所示:
fetch