I need to split one column in two based on some condition. Here is an example of table:
id | title
----------
1 | one
2 | two
3 | three
4 | four
So, I’d like to have a view with two columns like id1
and id2
, first one will contains ids that are lower than 3, second one – the rest ids, results should be consecutive. Expected result is
id1 | id2
----------
1 | 3
2 | 4
4
Answers
Without seeing more data, the exact requirement is not entirely clear. Here is one interpretation using
ROW_NUMBER()
with pivoting logic:Here is a working demo.
This should do the trick.
For simplicity I used a
JOIN
, if you can’t guarantee both parts have the same number of rows, you might have to use aLEFT
,RIGHT
orFULL OUTER JOIN
I put a working example on dbfiddle.
This approach compared to variants using
GROUP BY
is that all other columns can easily be used in the final query.This is compatible for mysql 5 :
Generally for a table of N rows
Returns