I have a table that looks as follows:
Book Format Contents
A html ...
A markdown ...
B html ...
C markdown ...
I want to return only 1 version of a book. If a markdown version exists, I want markdown, otherwise I want html.
I'd love to see a SELECT statement that does this, and also a reason why it works.
I think this query is very close to what I need, but I don't understand how it works.
Thanks!
Best Answer
One option is to use window functions to select those books:
The window function
row_number()
in the inner query assigns a number to each format.markdown
will get a1
everything else will get a2
.The outer select then gets those rows where there is a markdown available or where only a single format is available.
Another (faster) option is to use Postgres'
distinct on
operator:This again sorts on an expression that will give
markdown
a higher "priority" thanhtml
.The first solution is portable as it is ANSI SQL. The second one is Postgres specific.
SQLFiddle example: http://sqlfiddle.com/#!15/7a027/3