This does what your examples show, with the exception that I added commas so I could read the output. Note that your examples didn't show the '1' so I removed it.
The lines at the top are there so I could test it. I don't have your columns so I simulated them using variables. You can remove these lines and use the column lookup names directly.
The field author_sort contains the value calibre uses to sort. If there is more than one author, this template chooses the first author in the author_sort list.
The template language syntax is closer to visual basic than to excel. The
General Program Mode documentation might help.
This should be enough to get you going.
Code:
program:
# universe = $#universe;
# universe = 'Forgotten Realms';
universe = '';
# book_num = $#book_num
book_num = 26;
# sage = $#saga
# saga = 'Saga of Shannara';
saga = '';
# title = $title
title = 'Bearer of the Black Staff';
# author_sort = $#author_sort
author_sort = 'Brooks, Terry';
if universe then
strcat(universe, ', ', book_num)
elif saga then
strcat(list_item(author_sort, 0, '&'), ', ', saga, ', ', $id)
else
strcat(list_item(author_sort, 0, '&'), ', ', title)
fi