I have a problem in hand and that is to fetch a result set in a numeric pattern / sequence based on a single column’s value.
Say I have the following table:
+-------+
| val |
+-------+
| 1 |
| 1 |
| 1 |
| 1 |
| 2 |
| 2 |
| 2 |
| 2 |
| 3 |
| 3 |
| 3 |
| 3 |
+-------+
How can I make it this way instead:
+-------+
| val |
+-------+
| 1 |
| 2 |
| 3 |
| 1 |
| 2 |
| 3 |
| 1 |
| 2 |
| 3 |
| 1 |
| 2 |
| 3 |
+-------+
Case mentioned by aularon:
What if one of the values do not have enough to fill the gaps, what is the expected behaviour? Say we replace two of the 3’s to be 8’s
+-------+
| val |
+-------+
| 1 |
| 1 |
| 1 |
| 1 |
| 2 |
| 2 |
| 2 |
| 2 |
| 3 |
| 3 |
| 8 |
| 8 |
+-------+
I’d still expect it to go in numeric sequence of smallest first, then largest, then smallest, then largest.
+-------+
| val |
+-------+
| 1 |
| 2 |
| 3 |
| 8 |
| 1 |
| 2 |
| 3 |
| 8 |
| 1 |
| 2 |
| 1 |
| 2 |
+-------+
This is what we call a major
rownumhack. Let’s say your table is named t and your value column is named val. This will give the result you’re looking for.A word or two of explanation:
We need to turn your val table into
a val,n table (where n is the row
number)
Then we need two of those, with
independent row numbers @a and @b
Then we need to join them together
with a row = row-1 offset to compare
adjacent val columns.
Then we need to apply a sequence
number to each val column, that
resets. That is, we need to give
sequence numbers 1,2,3 to the 1s, then the 2s,
etc.
Then we need to sort by seq, then
val.
Then we need to conceal the seqs.
Lo and behold….
Hack hack!