I recently came across a Postgres SQL select test problem which I hadn't seen and had trouble coming up with the correct answer. A table basically contains page numbers and page titles for a book, and the object is to create a SELECT that will lay out the book as follows:
left_page, right_page
where left_page contains all even page #'s and right_page contains all odd page numbers, but where the 0 page shows null and where any non-consecutive page would have a null. There can be blank pages, so page numbers can skip.
My guess was to use the Lag or Lead functions to find the next page in order, then see if it was consecutive, but ran into problems.
Here's an example:
create table mysharkbook (page_no integer not null, title varchar(30) not null, unique(page_no));
insert into mysharkbook (page_no,title) VALUES (1,'Hammerhead');
insert into mysharkbook (page_no,title) VALUES (2,'Great White');
insert into mysharkbook (page_no,title) VALUES (3,'Blue');
insert into mysharkbook (page_no,title) VALUES (4,'Tiger');
insert into mysharkbook (page_no,title) VALUES (6,'Blacktip');
select * from mysharkbook;
Results
1 "Hammerhead"
2 "Great White"
3 "Blue"
4 "Tiger"
6 "Blacktip"
Now, try to get the SELECT to list like this:
left_page, right_page
null | Hammerhead
Great White | Blue
Tiger | null
Blacktip | null
Here was my (poor) attempt at it:
SELECT CASE WHEN prev_page IS NULL OR prev_page <> page_no - 1 OR (page_no % 2) = 0 THEN NULL ELSE title END As left_title,
CASE WHEN (page_no % 2) = 1 THEN title ELSE NULL END As right_title
FROM
(
SELECT LAG (page_no, 1) OVER (
ORDER BY
page_no
) AS prev_page,
title,page_no
from mysharkbook
order by page_no
) d
Any ideas on the best way?
Another:
select distinct on (page.no / 2)
msb.title, lead(msb.title) over(order by page.no)
from generate_series(0, (select max(page_no) from mysharkbook)) page(no)
left join mysharkbook msb on page.no = msb.page_no
order by page.no / 2
Output:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With