2

我需要在查询中按每学期使用一个分组。有谁知道有什么方法可以做到这一点?

如果我使用:

 `HAVING Date Between '2012-01 'and '2012-06'`

我相信它会起作用,但不会是查询的正确结果。

任何帮助表示赞赏

4

3 回答 3

6

你可以用这个——

+------+------------+
| 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 |
+------+----------+----------+
于 2012-08-14T09:39:16.777 回答
1

您无法通过以下方式获得任何日期学期:

FLOOR( ( MONTH(date)-1) / 6 ) + 1
于 2018-01-02T02:43:01.613 回答
0

我设法解决了仅获得第一学期或第二学期的问题,如下所示。

只获得第一学期:

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;

感谢所有帮助。

于 2012-08-15T16:32:57.290 回答