Suppose I have this table:
+-----+------+------------+
| 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 |
+-----+------+------------+
Now I want to get the records of number of employees in each department who joined after 1st January, 1983.
I tried this query:
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 |
+-------+------+
But I need all departments in one table.
select joining, dept, count(*)
from t1
group by dept
having(joining) > '1982-01-01'
order by joining;
No such result.
You need a simple group by clause with a where that filters the dates you want, like this:
select dept,count(*)
from t1
where joining > '1982-01-01'
group by dept
The having
clause is a condition applied on the groups created by the group by
clause. You need to use a simple where
clause which applies the condition to each row individually:
SELECT dept, COUNT(*)
FROM t1
WHERE joining > '1982- 01-01'
GROUP BY dept
Have you tried simply just moving your date into a WHERE clause, instead of having it in the GROUP BY, like this:
SELECT joining, dept, count(*)
FROM t1
WHERE joining > '1982-01-01'
GROUP BY dept
ORDER BY joining ACS;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.