Answer the question
In order to leave comments, you need to log in
How to filter records by the nearest date?
Hello! Please help me figure it out.
I have the following data model.
models.py:
class Securities(models.Model):
section = models.ForeignKey(Section)
characteristic = models.ForeignKey(Characteristics)
bool_value = models.NullBooleanField()
change_date = models.DateTimeField()
real_change_date = models.DateTimeField()
SECTION | CHARACTERISTIC | CHANGE_DATE | BOOL_VALUE
A | 8328 | 15.02.2018 | 1
A | 8328 | 02.09.2018 | 0
B | 8328 | 02.09.2018 | 1
C | 8328 | 02.09.2018 | 1
C | 8328 | 20.09.2018 | 0
SECTION | CHARACTERISTIC | CHANGE_DATE | BOOL_VALUE
C | 8328 | 20.09.2018 | 0
B | 8328 | 02.09.2018 | 1
A | 8328 | 02.09.2018 | 0
securities = Securities.objects.filter(characteristic=8328).order_by('-change_date').values_list('section').distinct()
print(securities.count())
to me, the number 33 is written. What is happening in general. How to solve this problem, friends?
Answer the question
In order to leave comments, you need to log in
select distinct on (section)
section,
characteristic,
change_date,
bool_value
from securities
where characteristic = 8328
group by id, section
order by section desc, change_date desc
select distinct on (section)
section
from accounts_securities
where characteristic = 8328
group by id, section
order by section desc, change_date desc
On sensations, the correlated subquery will rescue. Something like this:
SELECT * FROM securities t
WHERE t.change_date IN (SELECT Max(t1.change_date) FROM securities t1 WHERE t.section=t1.section)
If it works for a long time, then I suspect that you can come up with something more productive using analytic functions...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question