Get min and max row from table From a table with the columns: id(pk), type_id, book_id, title_id, page_id, lines(int4), created_at(date)

How can I select the row with min(lines) and max(lines) for (type_id, book_id, title_id, page_id) and also the value of created_at when min(lines) and the same for max value.

Dummy data:

type_id, book_id, title_id, page_id, lines, created_at
1, 1, 1, 1, 12, 2015-04-01
1, 1, 1, 1, 10, 2015-03-01
1, 1, 1, 1, 11, 2015-03-02
1, 1, 1, 2, 3, 2015-04-01
1, 1, 1, 2, 5, 2015-03-01
1, 1, 1, 2, 6, 2015-03-04


Expected output:

type_id, book_id, title_id, page_id, min, min_created_at, max, max_created_at
1, 1, 1, 1, 10, 2015-03-01, 11, 2015-03-02
1, 1, 1, 2, 3, 2015-04-01, 6, 2015-03-04
One way to do this is using window functions:

SELECT DISTINCT
    type_id, book_id, title_id, page_id,
    first_value(lines)      OVER wmin AS min_lines, 
    first_value(created_at) OVER wmin AS min_created_at, 
    first_value(lines)      OVER wmax AS max_lines,
    first_value(created_at) OVER wmax AS max_created_at
FROM 
    tableX
WINDOW 
    wmin AS (PARTITION BY type_id, book_id, title_id, page_id 
             ORDER BY lines ASC, created_at ASC), 
    wmax AS (PARTITION BY type_id, book_id, title_id, page_id 
             ORDER BY lines DESC, created_at ASC) ;


Tested at SQLfiddle.