I need to use a group by per semester in a query. Anyone know any way to do this?
If I use:
`HAVING Date Between '2012-01 'and '2012-06'`
I believe it will work, but will not be the correct result for the query.
Any help is appreciated
I need to use a group by per semester in a query. Anyone know any way to do this?
If I use:
`HAVING Date Between '2012-01 'and '2012-06'`
I believe it will work, but will not be the correct result for the query.
Any help is appreciated
You can use this one -
+------+------------+
| id | date |
+------+------------+
| 1 | 2012-08-14 |
| 2 | 2012-09-20 |
| 3 | 2012-05-14 |
| 4 | 2012-05-08 |
| 5 | 2012-08-16 |
+------+------------+
INSERT INTO table_name VALUES
(1, '2012-08-14'),
(2, '2012-09-20'),
(3, '2012-05-14'),
(4, '2012-05-08'),
(5, '2012-08-16');
SELECT
YEAR(date) year,
IF(MONTH(date) < 7, 1, 2) semester,
COUNT(*)
FROM
table_name
GROUP BY
year, semester;
+------+----------+----------+
| year | semester | COUNT(*) |
+------+----------+----------+
| 2012 | 1 | 2 |
| 2012 | 2 | 3 |
+------+----------+----------+
Using HAVING clause -
SELECT
YEAR(date) year,
IF(MONTH(date) < 7, 1, 2) semester,
COUNT(*)
FROM
table_name
GROUP BY
year, semester
HAVING
semester = 1
+------+----------+----------+
| year | semester | COUNT(*) |
+------+----------+----------+
| 2012 | 1 | 2 |
+------+----------+----------+
I managed to solve the problem of getting only the first semester or second semester just as follows.
To get only first semester:
SELECT
YEAR(date) year,
IF(MONTH(date) < 7, 1, 2) semester,
COUNT(*)
FROM
table_name
WHERE
MONTH(date) NOT IN(7,8,9,10,11,12)
GROUP BY
year, semester;
Thanks to all that helped.