Mysql-获取日期和日期之间的日期

时间:2017-06-14 06:43:50

标签: mysql

我有一个表 tbl_patient :包含from_date, to_date, patient_namegender

from_date    to_date      patient_name   gender

2017-06-10   2017-06-13   AAA            Male
2017-06-08   2017-06-11   BBB            Female
2017-06-13   2017-06-15   CCC            Male

我必须从 tbl_patient 创建一个新表 tbl_details ,其中包含来自from_date的{​​{1}}和to_date之间的日期),当天患者总数,男性人数和女性人数

tbl_patient

我的问题是我无法编写查询来查找from_date和to_date之间的日期

date          patients    Male    Female

2017-06-10    2           1       1
2017-06-11    2           1       1
2017-06-12    1           1       0
2017-06-13    2           2       0
2017-06-08    1           0       1
2017-06-09    1           0       1    
2017-06-14    1           1       0
2017-06-15    1           1       0

但没有运气..

请有人帮助我..

1 个答案:

答案 0 :(得分:0)

表:

create table tbl_patient (
    from_date date, 
    to_date date,
    patient_name varchar(45),
    gender varchar(45)
)

插入值

insert into tbl_patient values ('2017-06-10','2017-06-13','AAA','Male');
insert into tbl_patient values ('2017-06-08','2017-06-11','BBB','Female');
insert into tbl_patient values ('2017-06-13','2017-06-15','CCC','Male');

查询:

 set @mindate = (select min(from_date) - interval 1 day as mindate from tbl_patient);
set @maxdate = (select max(to_date) as mindate from tbl_patient);
select date_value, count(patient_name), count(case when gender = 'male' then 1 end) male, 
count(case when gender = 'female' then 1 end) female 

from (select @startDate := @startDate + Interval 1 day as date_value
from (select 0 union all select 1 union all select 3 union all select 4 
    union all select 5 union all select 6 union all select 6 union all select 7 
    union all select 8 union all select 9) t,
(select 0 union all select 1 union all select 3 
    union all select 4 union all select 5 union all select 6 
    union all select 6 union all select 7 union all select 8 union all select 9) t2,
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6 union all select 6 union all select 7 union all select 8 union all select 9) t3, 
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6 union all select 6 union all select 7 union all select 8 union all select 9) t4,
(SELECT @startDate := @mindate ) t5 
where @startDate < @maxdate ) generateCalendar

left join tbl_patient on date_value between from_date and to_date
group by date_value;

您也可以使用查询生成日历。找到最短和最长日期。

注意:最短日期应少于1天。