如何让sql查询在mysql的日期范围内每天返回一行?
我有一个具有这种结构的工作表:
job_id | station_id | start_date | end_date |
--------+---------------+---------------+---------------+
1 | 1 | 2017-06-01 | 2017-06-02 |
2 | 2 | 2017-06-01 | 2017-06-03 |
3 | 1 | 2017-06-02 | 2017-06-04 |
4 | 4 | 2017-06-01 | 2017-06-02 |
5 | 2 | 2017-06-04 | 2017-06-05 |
6 | 1 | 2017-06-06 | 2017-06-08 |
7 | 3 | 2017-06-01 | 2017-06-02 |
和一个电台表:
station_id | type |
-----------+------------|
1 | 1 |
2 | 1 |
3 | 2 |
4 | 2 |
5 | 2 |
如果我想知道2017-06-01中有多少2型电台正在使用,我可以很容易地做到这一点:
SELECT COUNT(job_id)
FROM jobs
WHERE start_date <= '2017-06-01'
AND end_date > '2017-06-01'
AND station_id IN (SELECT station_id FROM station WHERE type = 2);
这个例子告诉我们正在使用2个站(3和4):
+-------------+
|COUNT(job_id)|
+-------------+
| 2 |
+-------------+
但是, 我希望这会在一系列日期中每天返回一行 。
到目前为止,我已经用多次运行第一个查询的python脚本解决了这个问题, 有没有办法直接用mysql执行此操作? < / p>
编辑:根据user1960808的要求,范围2017-06-01 2017-06-03和类型2的预期结果将是:
+-----------+-------------+
| date |COUNT(job_id)|
+-----------+-------------+
|2017-06-01 | 2 |
|2017-06-02 | 0 |
|2017-06-03 | 0 |
+-----------+-------------+
答案 0 :(得分:0)
也许最简单的方法是生成范围:
select d.dte, count(job_id)
from (select '2017-06-01' as dte union all
select '2017-06-02' as dte
) d left join
jobs j
on j.start_date <= d.dte and j.end_date > d.dte
where j.station_id in (select station_id from station s where s.type = 2)
group by d.dte;
如果你有很多日期,这不是最有效的解决方案。
答案 1 :(得分:0)
检查
DELIMITER $$
Create Procedure GetJobRunningCount(dStartDate datetime,dEndDate datetime,dType int)
Begin
DROP TABLE IF EXISTS CountSummary;
CREATE TEMPORARY TABLE CountSummary(SelectedDate date,Count int);
While (dStartDate<=dEndDate) do
insert into CountSummary(SelectedDate,Count)
SELECT dStartDate,COUNT(1)
FROM jobs jo
inner join station st on(st.station_id=jo.station_id and type=dType )
WHERE start_date <= dStartDate
AND end_date > dStartDate;
set dStartDate=Date_add(dStartDate,interval 1 Day);
End while;
select * from CountSummary;
END$$
DELIMITER ;
call GetJobRunningCount('2017-06-01','2017-06-08',2)
答案 2 :(得分:0)
如果你可以创建一个如下面url所述的整数表,那么我认为可以通过以下查询来实现。
https://www.xaprb.com/blog/2005/12/07/the-integers-table/
创建整数表后的查询
SELECT job_id,station_id,start_date + INTERVAL i DAY, start_date,end_date
FROM job
INNER JOIN integers
ON i <= DATEDIFF(end_date,start_date)
AND station_id IN (SELECT station_id FROM station WHERE type = 2);