MySQL查询-按月获取合计

2022-03-08 00:00:00 mysql query-optimization

http://sqlfiddle.com/#!2/6a6b1

方案如上所示。我想做的就是得到销售总额/月的结果……用户将输入开始日期和结束日期,我可以(在PHP中)生成这些日期的所有月份和年份。例如,如果我想知道12个月的"销售"总数,我知道我可以运行12个具有开始和结束日期的查询,但是我只想运行一个结果如下的查询:

Month     numofsale
January - 2  
Feb-1
March - 23
Apr - 10

以此类推.

或者只是不带月份的销售列表,然后我可以将其与PHP中生成的月份数组配对.任何想法.

编辑/架构和从sqlfiddle.com粘贴的数据:

CREATE TABLE IF NOT EXISTS `lead_activity2` (
  `lead_activity_id` int(11) NOT NULL AUTO_INCREMENT,
  `sp_id` int(11) NOT NULL,
  `act_date` datetime NOT NULL,
  `act_name` varchar(255) NOT NULL,
  PRIMARY KEY (`lead_activity_id`),
  KEY `act_date` (`act_date`),
  KEY `act_name` (`act_name`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1  ;

INSERT INTO `lead_activity2` (`lead_activity_id`, `sp_id`, `act_date`, `act_name`) VALUES
(1, 5, '2012-10-16 16:05:29', 'sale'),
(2, 5, '2012-10-16 16:05:29', 'search'),
(3, 5, '2012-10-16 16:05:29', 'sale'),
(4, 5, '2012-10-17 16:05:29', 'DNC'),
(5, 5, '2012-10-17 16:05:29', 'sale'),
(6, 5, '2012-09-16 16:05:30', 'SCB'),
(7, 5, '2012-09-16 16:05:30', 'sale'),
(8, 5, '2012-08-16 16:05:30', 'sale'),
(9, 5,'2012-08-16 16:05:30', 'sale'),
(10, 5, '2012-07-16 16:05:30', 'sale');

解决方案

SELECT DATE_FORMAT(date, "%m-%Y") AS Month, SUM(numofsale)
FROM <table_name>
WHERE <where-cond>
GROUP BY DATE_FORMAT(date, "%m-%Y") 

检查您的小提琴演示中的以下内容它对我有效(删除where子句以进行测试)

SELECT DATE_FORMAT(act_date, "%m-%Y") AS Month, COUNT(*)
FROM lead_activity2
WHERE <where-cond-here> AND act_name='sale'
GROUP BY DATE_FORMAT(act_date, "%m-%Y") 

它返回以下结果

MONTH   COUNT(*)
07-2012 1
08-2012 2
09-2012 1
10-2012 3

相关文章