Mysql - 有可能使用Group By semester吗?

时间:2012-08-13 23:21:49

标签: mysql date group-by

我需要在查询中每学期使用一个组。有人知道怎么办?

如果我使用:

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

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

感谢任何帮助

3 个答案:

答案 0 :(得分:5)

你可以使用这个 -

+------+------------+
| 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 |
+------+----------+----------+

答案 1 :(得分: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;

感谢所有帮助。

答案 2 :(得分:0)

您无法获得任何日期学期:

>ssh-add
Enter passphrase for /Users/dan/.ssh/id_rsa:
Error loading key "/Users/dan/.ssh/id_rsa": Invalid key length

>ssh -V
OpenSSH_7.6p1, LibreSSL 2.6.2