Answer the question
In order to leave comments, you need to log in
How to write a complex SQL query?
Hello colleagues!
Today I faced a difficult task for which I did not have enough skills. I turn to the community for help.
So, there is a history table with something like this structure:
id | task_id | phrase_id | date | position
Some historical data gets into this table - some tasks are performed once or several times a day, which simply write a new position (int) by the phrase (int) and the current time (timestamp) to this table .
The task is to extract summary information in one query: how many phrase positions increased, how many positions sank, how many positions remained unchanged during the last check compared to the previous check for each task for all phrases belonging to this task.
DBMS - postgresql.
Help, pliz, the brain breaks.
Answer the question
In order to leave comments, you need to log in
Is each check a holistic slice of data? That is, it may be that for phrase 5 the last check was in 2020-07-05, and for phrase 6 it is necessary to rewind in 2020-07-03?
In general, we eat an elephant in parts:
extract summary information: how many phrase positions increased, how many positions sank, how many positions remained unchanged
select count(*) filter(where r1.position < r2.position) as pos_down,
count(*) filter(where r1.position = r2.position) as pos_same,
count(*) filter(where r1.position > r2.position) as pos_up from ...
tablename r1 full join tablename r2 on r1.phrase_id = r2.phrase_id where r1.... and r2....
where r2.task_id = 123 and r1.task_id in (select id from tasks where id < 123 order by id desc limit 1)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question