我的表格中确实有旅行,其中有开始日期和结束日期,例如
id | 开始日期 | 结束日期 |
---|---|---|
1 | 2025-06-13 | 2025-06-13 |
2 | 2025-06-12 | 2025-06-17 |
3 | 2025-06-20 | 2025-06-21 |
4 | 2025-05-31 | 2025-06-02 |
等等。我现在需要的是每天的游览次数,即使这一天没有游览。我的查询有几个问题:
SELECT start_date, COUNT(id) AS numberOfTours FROM tour WHERE start_date >= '2025-06-01' AND start_date =< '2025-06-30' GROUP BY start_date ORDER BY start_date;
我看到的 3 个问题是:
start_date
。由于旅行可能持续超过一天,这会造成错误计数2025-05-31
但结束于 2025-06-02
的游览)。完美的结果应该是这样的:
日期 | 游览次数 |
---|---|
2025-06-01 | 1 |
2025-06-02 | 1 |
2025-06-03 | 0 |
2025-06-04 | 0 |
2025-06-05 | 0 |
2025-06-06 | 0 |
2025-06-07 | 0 |
2025-06-08 | 0 |
2025-06-09 | 0 |
2025-06-10 | 0 |
2025-06-11 | 0 |
2025-06-12 | 1 |
2025-06-13 | 2 |
2025-06-14 | 1 |
2025-06-15 | 1 |
2025-06-16 | 1 |
2025-06-17 | 1 |
2025-06-18 | 0 |
2025-06-19 | 0 |
2025-06-20 | 1 |
2025-06-21 | 1 |
2025-06-22 | 0 |
2025-06-23 | 0 |
2025-06-24 | 0 |
2025-06-25 | 0 |
2025-06-26 | 0 |
2025-06-27 | 0 |
2025-06-28 | 0 |
2025-06-29 | 0 |
2025-06-30 | 0 |
如果有任何帮助:我有一个
day
表,其中每一天都由一行表示。
SELECT date,
(SELECT COUNT(id)
FROM tour
WHERE tour.start_date <= day.date
AND tour.end_date >= day.date
) AS numberOfTours
FROM day
WHERE date > '2025-07-01'
AND date < '2025-07-31'
ORDER BY date;
很简单:)