1

I have this table in my database:

enter image description here

I want to get 2 columns: id_chantier and id_chef.
Conditions: date_fin not null and has the last date_deb.
So the rows that I want to get are number 1 and 11.
How can I do that?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
SlimenTN
  • 3,383
  • 7
  • 31
  • 78
  • and row 8?.. what you mean "has the last date_deb"?.. – Vao Tsun Mar 31 '15 at 10:50
  • 1
    Can you post the query you've currently got, also can you clarify why you want rows 1 and 11, not just 11 (11 has 2015-03-23, which is later than 1's 2015-01-23)? – GHC Mar 31 '15 at 10:50
  • Shouldn't that be *only* row 11? Why is row 1 included? It would make sense to include 1 if `date_deb` were 2015-03-23. – Gordon Linoff Mar 31 '15 at 10:52
  • i want to get the list of sites (chantier) that are closed (date_fin is not null) and the last worked chief for each site – SlimenTN Mar 31 '15 at 11:10
  • Typically, it is better to provide data as text. We cannot copy / paste from an image. And remember to provide your version of Postgres. – Erwin Brandstetter Mar 31 '15 at 11:17

3 Answers3

1
SELECT DISTINCT ON (id_chef)
       id_chantier, id_chef
FROM   tbl
WHERE  date_fin IS NOT NULL
ORDER  BY id_chef, date_deb DESC NULLS LAST;

Details for DISTINCT ON

Depending on data distribution there may be faster solutions:

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
0

You can do this with rank():

select id_chantier, id_chef
from (select t.*, rank() over (order by date_deb desc) as rnk
      from table t
     ) t
where date_fin is not null and rnk = 1;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

-- I want to get the list of sites (chantier) that are closed (date_fin is not null)

SELECT *
FROM ztable t
WHERE date_fin IS NOT NULL
AND NOT EXISTS (
    SELECT * FROM ztable nx
    WHERE nx.id_chantier = t.id_chantier -- Same site
    AND nx.date_fin > t.date_fin         -- more recent
    );
joop
  • 4,330
  • 1
  • 15
  • 26