2017-06-14 53 views
0

我有一个表格tbl_patient:包含from_date, to_date, patient_namegenderMysql-从日期到日期之间的日期

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_patientfrom_dateto_date之间),患者在当天TOTAL_NUMBER,女

的男性和数量的数创建一个新表 tbl_details
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 

我的问题是我无法写入查询查找FROM_DATE和TO_DATE

之间的日期10
I tried 

SELECT DATE_ADD(MIN(from_date), interval @num := @num+1 day) AS date_sequence, 
tbl_patient.* FROM tbl_patient 
HAVING DATE_ADD(MIN(from_date), interval @num day) <= MAX(to_date) 

,但没有运气..

请有人可以帮助我..

+0

患者和您的预期输出日期之间的逻辑是什么?为什么在10-06和11-6有2个病人,12-06只有1个? –

+0

您是否正在寻找一种查询,让您每天在从和到之间分为男性/女性的患者数量? – avisheks

+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天。

+0

@ next2u已更新回答。让我知道它是有用的或不是。 –

+0

'generateCalendar'是什么?如何使用这个? – next2u

+0

@ next2u GenerateCalender不过是生成包含开始日期和结束日期之间所有日期的行。你是否用你的数据执行了上面的查询? –