2

好的,这是我的问题。我试图在这些年来每月获得专辑数量。这是我的查询

SELECT DATE(a.date), COUNT(a.id) 
FROM album a 
JOIN event e ON e.id = a.event_id  
WHERE  YEAR(a.date) >= 2001 
AND e.client_id = 89 
GROUP BY MONTH(a.date) 
ORDER BY a.date DESC

返回的结果是

+--------------+-------------+
| DATE(a.date) | COUNT(a.id) |
+--------------+-------------+
| 2011-09-09   |          15 |
| 2011-08-26   |           9 |
| 2010-01-01   |          28 |
| 2006-03-03   |          20 |
| 2005-12-02   |          20 |
| 2005-11-11   |          15 |
| 2005-10-07   |          13 |
| 2005-07-01   |          12 |
| 2005-06-03   |           6 |
| 2005-05-06   |          18 |
| 2005-04-15   |          15 |
| 2005-02-04   |          22 |
+--------------+-------------+
12 rows in set (0.00 sec)

这个结果集缺少 2012 年的结果但是如果我写这个

SELECT DATE(a.date), COUNT(a.id)
FROM album a 
JOIN event e ON e.id = a.event_id 
WHERE 
YEAR(a.date) > 2005
AND e.client_id = 89 GROUP BY MONTH(a.date)
ORDER BY a.date DESC;

现在我得到了 2012 年,但我错过了 2005 年:/ 有人可以向我解释一下吗?

+--------------+-------------+
| DATE(a.date) | COUNT(a.id) |
+--------------+-------------+
| 2012-06-01   |           2 |
| 2012-05-04   |          14 |
| 2012-04-06   |          13 |
| 2011-12-02   |          10 |
| 2011-11-04   |           9 |
| 2011-10-07   |          10 |
| 2011-09-09   |           9 |
| 2011-08-26   |           6 |
| 2010-01-01   |          26 |
| 2006-07-07   |           8 |
| 2006-03-03   |          19 |
| 2006-02-03   |          16 |
+--------------+-------------+
12 rows in set (0.01 sec)
4

1 回答 1

2

您正在分组,MONTH所以我相信您所有的年度数据都被合并为一个计数(请注意,您每次获得 12 行,每个月 1 行)。我想你可以通过按年和月分组来解决这个问题......

GROUP BY YEAR(a.date)
GROUP BY MONTH(a.date)

(无论如何,对于第一种情况,对于第二种情况,您不会通过调用获得 2005 年的数据year > 2005,正如 silly 指出的那样)

于 2012-07-12T13:48:05.020 回答