I am looking for SQL-Query that can match a set of individual size elements with a set of individual size buckets.
I would like to satisfy the following conditions:
- The bucket size must be greater than or equal to the size of the item.
- Each bucket can contain only one item or it remains empty.
- Each item can only be placed in one bucket.
- No element can be divided into several buckets.
- I want to fill the buckets so that the smallest unused buckets are filled first.
- Then the initial elements and the elements of the set can be ordered by size or id, but are not incremental
- The sizes and identifiers of the initial set of bucket and elements may be arbitrary and not begin with a known minimum value
- The result should always be correct if a valid mapping exists.
- The result may be incorrect if the match is invalid (for example, if there are more elements than buckets), but I would be grateful if the result would be empty or have another property / signal that indicates an incorrect result.
To give you an example, let's say the tables of my carpets and elements look like this:
Bucket: Item:
+---------------------+ +---------------------+
| BucketID | Size | | ItemID | Size |
+---------------------+ +---------------------+
| 1 | 2 | | 1 | 2 |
| 2 | 2 | | 2 | 2 |
| 3 | 2 | | 3 | 5 |
| 4 | 4 | | 4 | 11 |
| 5 | 4 | | 5 | 12 |
| 6 | 7 | +---------------------+
| 7 | 9 |
| 8 | 11 |
| 9 | 11 |
| 10 | 12 |
+---------------------+
Then I would like to have a mapping that returns the following table of results:
Result:
+---------------------+
| BucketID | ItemID |
+---------------------+
| 1 | 1 |
| 2 | 2 |
| 3 | NULL |
| 4 | NULL |
| 5 | NULL |
| 6 | 3 |
| 7 | NULL |
| 8 | 4 |
| 9 | NULL |
| 10 | 5 |
+---------------------+
-, ( Bucket.Size >= Item.Size) SQL . , , , (, 2 12, 2 ), .
, , , SQL, , .
, SQL? , , .
: , , Oracle, Postgres SQLite
Edit II: SQL , , , http://sqlfiddle.com/#!15/a6c30/1
user3112922