1
Good morning, you guys. I have a question regarding a grouping of data in postgresql and I would like to know if you can help me.
I have a database containing a table with entry times in an establishment, and another table with exit times. Both have in common a ticket number, which would be my id. I need to group the values so that I can match the nearest entry and exit times, according to your ticket. Isolating a specific ticket, I got the following data:
entrada ticket
------------------- --------
2020-12-02 07:53:02 802
2020-12-03 09:00:07 802
saida ticket
------------------- --------
2020-12-02 16:42:12 802
2020-12-03 17:22:21 802
To try to join this data, I have run the following SQL command:
select e.data as data_entrada, e.ticket as num_ticket, s.data as data_saida from entrada e
join saida s on e.ticket = s.ticket
group by data_entrada, data_saida, num_ticket
having e.ticket = '802'
order by data_entrada, data_saida
Result obtained:
data_entrada num_ticket data_saida
-- ------------------- -------- -------------------
0 2020-12-02 07:53:02 802 2020-12-02 16:42:12
1 2020-12-02 07:53:02 802 2020-12-03 17:22:21
2 2020-12-03 09:00:07 802 2020-12-02 16:42:12
3 2020-12-03 09:00:07 802 2020-12-03 17:22:21
Expected result:
data_entrada num_ticket data_saida
-- ------------------- -------- -------------------
0 2020-12-02 07:53:02 802 2020-12-02 16:42:12
3 2020-12-03 09:00:07 802 2020-12-03 17:22:21
Would anyone have a solution proposal, either by SQL or even by Python? Apparently it’s simple, but I got lost in the query and I couldn’t find a solution yet. Thanks from now.
One possibility is to subselect the lowest exit date that is greater than or equal to the ticket entry date.
– anonimo
I believe it’s enough to do the
on e.ticket = s.ticket and e.data_entrada = s.data_entrada
– Paulo Marques
The same
num_ticket
may have more than onedata_entrada
ordata_saida
same day? If so, what is the expected result?– Terry
@Terry yes, you can. In this case you would do the combination with the nearest ordered record. But having a solution for this sample I can try to derive the rest of the solution later.
– jhenrique