显示具有最高日期属性的行,用于共享相同名字的行

时间:2014-03-28 23:54:58

标签: sql postgresql greatest-n-per-group

Desc

我想显示具有相同名字的记录的最高投递日期的记录。我将如何继续这样做?

2 个答案:

答案 0 :(得分:0)

使用可以使用ROW_NUMBER窗口函数来完成此操作。 请参阅:http://www.postgresql.org/docs/9.3/static/sql-expressions.html#SYNTAX-WINDOW-FUNCTIONShttp://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
;

答案 1 :(得分:0)

这是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;

详细说明:
Select first row in each GROUP BY group?