2

我有一个包含这些字段的表

id    sell_date   
a1    27/7/2012
a1    26/7/2012
a1    24/7/2012
a1    24/2/2012

我想要计算当前日期前一年内销售的月份。结果

a1 = 2

4

2 回答 2

4

假设 sell_date 是 DATE 类型:

SELECT COUNT(DISTINCT MONTH(sell_date)) FROM `mytable` 
    WHERE id='a1' 
    AND sell_date>=DATE_SUB(NOW(),INTERVAL 1 YEAR);

还,

删除id='a1' AND将为您提供与任何 id 关联的销售额(在去年期间)的月数。像这样:

SELECT COUNT(DISTINCT MONTH(sell_date)) FROM `mytable` 
    WHERE sell_date>=DATE_SUB(NOW(),INTERVAL 1 YEAR);

还,

您可以获得每个 id 的列表以及去年与该 id 关联的销售额的月数,如下所示:

SELECT COUNT(DISTINCT id,MONTH(sell_date)) FROM `mytable` 
    WHERE sell_date>=DATE_SUB(NOW(),INTERVAL 1 YEAR);
于 2012-07-27T16:44:52.263 回答
3

您需要 datediff() 函数:

select count(id) as N 
from table_name
where datediff(curdate(), sell_date) >= 365;

http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_datediff http://dev.mysql.com/doc/refman/5.1/en/date-and -time-functions.html#function_curdate

于 2012-07-27T16:42:15.357 回答