我需要在查询中按每学期使用一个分组。有谁知道有什么方法可以做到这一点?
如果我使用:
`HAVING Date Between '2012-01 'and '2012-06'`
我相信它会起作用,但不会是查询的正确结果。
任何帮助表示赞赏
你可以用这个——
+------+------------+
| 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 |
+------+----------+----------+
使用 HAVING 子句 -
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 |
+------+----------+----------+
您无法通过以下方式获得任何日期学期:
FLOOR( ( MONTH(date)-1) / 6 ) + 1
我设法解决了仅获得第一学期或第二学期的问题,如下所示。
只获得第一学期:
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;
感谢所有帮助。