All,
We are having a problem with sorting the results of a database query.
The result of the query will be used to calculate discount to a customer. The table is then read from right to left.
However, the problem we are facing, is that we are unable to find a proper sort method to sort the results of this query.
The expected result looks like this, where the first line has the highest priority and the last line the lowest priority:
0 0 0 0 1
0 0 0 1 1
0 0 0 1 0
0 0 1 1 1
0 0 1 0 1
0 0 1 1 0
0 0 1 0 0
0 1 1 1 1
0 1 0 1 1
0 1 1 0 1
0 1 0 0 1
0 1 1 1 0
0 1 0 1 0
0 1 1 0 0
0 1 0 0 0
1 1 1 1 1
1 0 1 1 1
1 1 0 1 1
1 0 0 1 1
1 1 1 0 1
1 0 1 0 1
1 1 0 0 1
1 0 0 0 1
1 1 1 1 0
1 0 1 1 0
1 1 0 1 0
1 0 0 1 0
1 1 1 0 0
1 0 1 0 0
1 1 0 0 0
1 0 0 0 0
Hope anyone has a solution for sorting this result list.
If posible preferable in SQL.
Kind regards, Pieter Jong
I think you mixed up two lines,
1 1 1 0 1and1 0 0 1 1? If so, the comparison rule is: Find the first1from the left in either sequence. If the other sequence has a0there, it has higher priority; otherwise compare the sequences from the right.Stated another way: Consider the sequences as binary numbers without leading zeros; shorter numbers have higher priority; if two numbers have equal length, reverse them, and the greater one has priority.
Stated yet another way: Read the sequences as binary numbers from right to left, then sort them first according to the number of factors of $2$ they contain and then according to the numbers themselves.
Stated yet another way: Read the sequences as binary numbers from right to left, write them as $2^km$ and sort the pairs $(k,m)$ in lexicographical order.