I have a query that uses union to join two sub queries e.g.
SELECT * FROM posts WHERE postTypeId=1 (e.g. blog)
UNION
SELECT * FROM posts WHERE postTypeId=2 (e.g. news)
The result set that this approach generates positions the two sub-sets sequentially (“blog” then “news”).
I want to create a a result set which interleaves the two, alternating between rows from the “blog” sub-set and the “news” sub-set.
I feel that there must be a simple way to do this, but I have failed to find it.
Any suggestions would be greatly appreciated.
Nick
This is solution that best works for me. It’s not identical to any of the current proposals, so I have added it independently. @a, @b and @c are used to create row numbers per sub-set, meaning that in the combined results, 3 rows will share the same row number (a “row set”). This is used as the first order sort, and second order sort then orders the rows within the “row set”.
This solutions is derived/inspired by submitted solutions, but I don’t think it appropriate to mark any of them as being an accepted solution in itself. So, credit where it’s due to Thomas Clayson, Tony Hopkinson and rmunoz whose answers I’ve voted up. Cheers!