-1

Desc

I want to display the record with the highest slot date for the records that share the same first name. How would I proceed on doing that?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
hero
  • 15
  • 3
  • i have no clue thats why i want a headsup – hero Mar 29 '14 at 00:39
  • it is much easier if you post the text of your SQL query instead of a screenshot. – BateTech Mar 29 '14 at 00:56
  • set search_path = 'project'; select E.firstname,S.category , S.showname ,O.slotdate from hostsshows H , Shows S , Host E ,timeslot O where S.shownumber = H.shownumber AND H.empnum = E.empnum AND O.shownumber = H.shownumber – hero Mar 29 '14 at 01:33
  • We *very much* prefer text over images for code. One cannot copy/paste from images. – Erwin Brandstetter Mar 29 '14 at 04:53

2 Answers2

0

Use can use the ROW_NUMBER windowed function to accomplish this. See: http://www.postgresql.org/docs/9.3/static/sql-expressions.html#SYNTAX-WINDOW-FUNCTIONS and http://www.postgresql.org/docs/9.3/static/tutorial-window.html

SELECT * 
FROM 
(
SELECT E.firstname
    , S.category 
    , S.showname 
    , O.slotdate
    , ROW_NUMBER() over(PARTITION BY E.firstname ORDER BY O.slotdate DESC) as rowNum
FROM hostshows H , Shows S , Host E ,timeslot O
WHERE S.shownumber = E.shownumber
AND H.empnum = E.empnum
AND O.shownumber = H.shownumber
) t
WHERE rowNum = 1
;
BateTech
  • 5,780
  • 3
  • 20
  • 31
0

This is a textbook example for DISTINCT ON:

SELECT DISTINCT ON (e.firstname)
       e.firstname, s.category, s.showname, o.slotdate
FROM   shows     s 
JOIN   host      e USING (shownumber)
JOIN   timeslot  o USING (shownumber)
JOIN   hostshows h USING (empnum)
ORDER  BY e.firstname, o.slotdate DESC;

Detailed explanation:
Select first row in each GROUP BY group?

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