从两个不同年份的当前日期(月)获取月份和记录列表

时间:2015-12-08 07:12:00

标签: mysql sql date mysql-workbench

我在mysql数据库的表中有这样一组记录;

Date                | Number_of_leaves
10th-December-2015  |   10 leaves 
6th-August-2015     | 10 leaves
15th-September-2015 |  14 leaves
15th-January-2016:  |   100 leaves
7th-November-2015:  |  4 leaves
9th-October -2015:  |  200 leaves

如何从2016年1月起退回过去4个月的月份及其记录?换句话说,我需要过去4个月的结果,包括当前的结果:

January 2016  |  100 leaves
December 2015 | 10 leaves
November 2015 | 4 leaves
October 2015  |  200 leaves

以上是显示当月和相应年份收集的月数和相应年份的结果

2 个答案:

答案 0 :(得分:1)

模式

create table xyz
(   id int auto_increment primary key,
    theDate date not null,
    leaves int not null
);

-- truncate table xyz;
insert xyz(theDate,leaves) values
('2016-04-10',444510), 
('2016-02-10',55510), 
('2015-12-10',10), 
('2015-08-06',10),
('2015-09-15',14),
('2016-01-15',100),
('2015-11-07',4), 
('2015-10-09',200);

查询1

select month(theDate) as m,
year(theDate) as y,
sum(leaves) as leaves
from xyz
where theDate<='2016-02-01'
group by month(theDate),year(theDate)
order by theDate desc
limit 4;

查询2

select concat(monthname(theDate),' ',year(theDate)) as 'Month/Year', 
sum(leaves) as leaves 
from xyz 
where theDate<='2016-02-01' 
group by month(theDate),year(theDate) 
order by theDate desc 
limit 4;

+---------------+--------+
| Month/Year    | leaves |
+---------------+--------+
| January 2016  |    100 |
| December 2015 |     10 |
| November 2015 |      4 |
| October 2015  |    200 |
+---------------+--------+

答案 1 :(得分:0)

op是您的表名,首先使用str_to_date将字符串转换为日期格式。我们使用if因为您的日期格式不同

select * FROM (
SELECT *,
IFNULL(
    IFNULL(
    str_to_date(Date,'%D-%b-%Y'),str_to_date(Date,'%d-%M-%Y')) ,
    str_to_date(Date,'%D-%M-%Y')
    )    
f_date     
FROM `op` 
order by number_of_leaves DESC,f_date ASC    
) tab
group by month(tab.f_date) LIMIT 5