我有两个表项目和资助项目。
产品表就像,
+-----------------+
| id | date_created |
+-----------------+
| 1 | 2014-09-10 |
| 2 | 2014-05-20 |
| 3 | 2014-02-20 |
| 4 | 2014-02-20 |
+-----------------+
我的project_funded表就像,
+------------------------------+
| id | date_funded | Proj_id |
+------------------------------+
| 1 | 2014-09-10 | 1 |
| 2 | 2014-09-11 | 1 |
| 3 | 2014-09-11 | 1 |
| 4 | 2014-09-12 | 1 |
+------------------------------+
现在如何获取项目 1 从开始日期起的接下来 1 周的数据计数
。
例如,Project_id 1 于 2014 年 9 月 10 日启动,
我需要这样的结果,
2014-09-10 => 1
2014-09-11 => 2
2014-09-12 => 1
最佳答案
这是一个带有分组依据的基本查询...
select
pf.date_funded,
count(*) as totalEntries
from
project_funded pf
where
pf.proj_id = 1
group by
pf.date_funded
order by
pf.date_funded
现在,如果您只关心项目创建日期后的 1 周,则需要对项目表进行额外的联接,并且需要基于项目创建日期的日期范围限制。
select
pf.date_funded,
count(*) as totalEntries
from
project_funded pf
JOIN project p
on pf.proj_id = p.id
where
pf.proj_id = 1
AND pf.date_funded >= p.date_created
AND pf.date_funded < DATE_ADD(p.date_created, INTERVAL 8 DAY);
group by
pf.date_funded
order by
pf.date_funded
在上面的日期示例中,您提到了 1 周(7 天),这可能是 INTERVAL 1 WEEK。但是,如果您的日期是基于日期/时间的,那么您确实需要 11:59:59 之前的所有 7 天(包括晚上 11:59:59)。这就是为什么我做了不到 8 天的原因 - 所以它包括从 7 天到第 8 天前一天晚上结束的所有方式。
关于Mysql 选择特定日期1周的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25807784/