Take only the first record of each condition

Asked

Viewed 54 times

1

Good afternoon!

I have the following table:

inserir a descrição da imagem aqui

How to get only the first record of each id_uni_sching? That is, I need to get the id_sching 534,382 and 524,075 (First time of each id_uni_sching) ?

Note: I am using Postgres

2 answers

2


You can add using the array_agg function and access the index of the item you want, if you sort by some column with timestamp is perfect.

select id_uni_sching,
      (array_agg(id_sching order by sta_sching))[1] as primeiro_id_sching,
      (array_agg(dta_sching order by sta_sching))[1] as primeiro_dta_sching,
      (array_agg(sta_sching order by sta_sching))[1] as primeiro_sta_sching
from seguinte_tabela
group by id_uni_sching

You can do the opposite by sta_sching desc, Okay, I’m assuming that sta_sching is a time column, if you don’t have to go a little deeper by creating a subquery for row_number(). In this case you can assign a number to each Row, and sort by this number.

  • I didn’t know the array_agg function, very interesting and it worked perfectly! Thanks Marcos, hugs.

  • I get wrong results, data - ('23ef', 534.383, '12-02-2021', '09:00'), ('23ef', 534.382, '12-03-2021', '11:30'), ('23ef', 534.389, '12-02-2021', '08:30'), ('c557', 524.075, '12-02-2021', '08:00'), ('c557', 524.085, '12-02-2021', '07:00'), ('c557', 524.090, '12-02-2020', '19:00'), ('c557', 524.076, '12-02-2021', '08:30')

  • given that I am seeing 2ef repeating as id_uni, I believe that you have not grouped by id_uni.. Whenever q vc adds a column, vc has q group the remaining q will be repeated.. so any repeated value is condensed into a single Row along with the aggregated values.

  • Why we get different results? Try to

1

A solution using DISTINCT ON:

SELECT DISTINCT ON (id_uni_sching) id_uni_sching, id_sching, dta_sching, sta_sching
FROM tabela1
ORDER BY id_uni_sching, dta_sching, sta_sching;
  • 1

    hmm.. I do not know if it solves, but it is new to me that distinct on(), only knew distinct about all columns haha.. vlws by sharing aew

Browser other questions tagged

You are not signed in. Login or sign up in order to post.