如何获得本月的记录数?

时间:2014-02-11 01:31:40

标签: mysql

如何获得本月的记录数?

我想算这个月的用户? "本月"应该由mysql本身计算。怎么写sql?

enter image description here

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `a`
-- ----------------------------
DROP TABLE IF EXISTS `a`;
CREATE TABLE `a` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(30) default NULL,
  `date` datetime default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of a
-- ----------------------------
INSERT INTO `a` VALUES ('1', 'jimy', '2014-02-11 09:24:42');
INSERT INTO `a` VALUES ('7', 'khon', '2014-02-19 09:24:50');
INSERT INTO `a` VALUES ('3', 'tina', '2014-01-11 09:25:03');
INSERT INTO `a` VALUES ('4', 'kelvin', '2013-12-11 09:25:09');
INSERT INTO `a` VALUES ('5', 'ricky', '2014-02-12 09:25:14');

2 个答案:

答案 0 :(得分:2)

你可以试试这个

Select    count(*) 
FROM      a 
WHERE     MONTH(date) = MONTH(NOW())
GROUP BY  MONTH(date)

答案 1 :(得分:1)

MONTH(日期)仅返回月份数,不适用于多年数据。

SELECT COUNT(*) count
FROM a
WHERE EXTRACT(YEAR_MONTH FROM a.date) = EXTRACT(YEAR_MONTH FROM NOW()) 

或者您可以使用:

SELECT COUNT(*) count
FROM a
WHERE DATE_FORMAT(a.date,'%Y%m') = DATE_FORMAT(NOW(),'%Y%m')