我有一个名为 Billing 的表,其中包含以下列
id| resource_name | start_date | end_date | total_amount
此表中填充了具有不同开始日期和结束日期的不同资源的数据。我需要从表中检索数据。
id| resource_name | start_date | end_date | total_amount
1 | abc | 2018-09-15 03:00:00 | 2018-09-15 04:00:00 | 20
如果我写这样的查询,它将返回上面的结果
select * from billing where start_date >= '2018-09-15 03:00:00' and end_date <= '2018-09-15 04:00:00'
但是下面没有
select * from billing where start_date >= '2018-09-15 03:00:00' and end_date <= '2018-09-15 03:30:00'
有什么方法可以检索相同的。我正在使用Django ORM进行同样的操作
答案 0 :(得分:1)
您可以使用django过滤器方法。
Billing.objects.filter(start_date__gte='2018-09-15 03:00:00', end_date__lte='2018-09-15 03:30:00')
答案 1 :(得分:0)
这个问题有点令人困惑,但是如果您要获取与指定时间段完全重叠的所有订单,则需要对查询进行一些修改:
Billing.objects.filter(start_date__lte='2018-09-15 03:30:00', end_date__gt='2018-09-15 03:00:00')
否,这写得不正确。您需要反转原始查询中的日期和gte / lte。
IE: Billing.objects.filter(start_date__lte='the end datetime of your time period', end_date__gt='the start datetime of your time period')
这将确保包括与03:00至03:30块完全重叠的所有订单。所有这些都将包括在内:
id| resource_name | start_date | end_date | total_amount
1 | abc | 2018-09-15 03:00:00 | 2018-09-15 04:00:00 | 20
2 | abd | 2018-09-15 02:00:00 | 2018-09-15 03:00:01 | 20
3 | abe | 2018-09-01 03:00:00 | 2018-09-20 04:00:00 | 20
4 | abf | 2018-09-15 03:10:00 | 2018-09-15 03:20:00 | 20
但是以下内容不会:
id| resource_name | start_date | end_date | total_amount
5 | abg | 2018-09-15 02:00:00 | 2018-09-15 03:00:00 | 20
6 | abh | 2018-09-15 03:30:01 | 2018-09-15 04:00:00 | 20
如果您要查找特定时段内的订单,请使用Aman Kumar的答案。
答案 2 :(得分:0)
最后我得到了pgsql解决方案。但不确定如何将其转换为Django ORM
SELECT * FROM billing_lines WHERE (start_date, end_date) OVERLAPS ('2018-09-15 03:00:00', '2018-09-15 03:30:00');