结合多个SQL选择查询的结果

时间:2016-10-25 09:08:11

标签: mysql sql

我有一个表格,其中包含open_date和close_date字段。我必须创建一个过程,给定一系列日期作为输入,我显示该范围内的每个日期的所有记录,open_date> date和closed_date的记录

例如,如果我的表是

id   open_date    closed_date
1    2016-06-06   2016-06-10
2    2016-06-08   2016-06-11

且日期范围为2016-06-07至2016-06-09

然后结果应该是

Date          Count
2016-06-07      1
2016-06-08      2
2016-06-09      2

但我得到的结果是

 Date          Count
2016-06-09      2

我写下的程序如下:

CREATE DEFINER=`root`@`localhost` PROCEDURE `find_number_of_bugs`(IN startDate DateTIme, IN endDate DateTime)
BEGIN
Declare testDate Date;
SET testDate=startDate;
while testDate<=endDate DO
select testDate as Dates ,count(bugID) as Number_Of_Bugs_Open from bugs where testDate between open_date and close_date OR close_date=null;
SET testDate=DATE_ADD(testDate,INTERVAL 1 DAY);
END while;
END

我想我必须结合多个select语句的结果 在while循环中运行throgh。请建议我这样做的方法。

1 个答案:

答案 0 :(得分:0)

您正在剔除所有结果,但是在多个结果集中。 您可以将所有查询结果保存在临时表中,并在最后查询一次。

CREATE DEFINER=`root`@`localhost` PROCEDURE `find_number_of_bugs`(IN startDate DateTIme, IN endDate DateTime)
BEGIN
Declare testDate Date;
SET testDate=startDate;

CREATE TEMPORARY TABLE output (Dates date,Number_Of_Bugs_Open int);

while testDate<=endDate DO

insert into output select testDate as Dates ,count(bugID) as Number_Of_Bugs_Open from bugs where testDate between open_date and close_date OR close_date=null;

SET testDate=DATE_ADD(testDate,INTERVAL 1 DAY);
END while;

select * from output;

END
相关问题