I have a table Containers with following data:
Name | CapacityNormal | CapacityMax
-------------+----------------+------------
Container #1 | 2 | 2
Container #2 | 2 | 3
Container #3 | 2 | 4
Container #4 | 3 | 4
Container #5 | 3 | 5
And a variable Quantity. I want to sort containers with respect to quantity in this order:
- containers whose capacity normal is greater than/equal to quantity
- containers whose capacity max is greater than/equal to quantity
- everything else
Note that:
- Wasting normal slots is not desireable
- Exceeding normal capacity incurs a pealty
Keeping the above in mind the ties must be broken according to these rules:
- containers with smallest wasted normal capacity
- containers with smallest penalty
If Quantity = 3 the expected output would be:
Name | CapacityNormal | CapacityMax | Comment
-------------+----------------+-------------+-------------------------------------------
Container #4 | 3 | 4 | wastes 0 slots
Container #5 | 3 | 5 | wastes 1 slot
Container #2 | 2 | 3 | exceeds normal capacity, incurs 1 penalty
Container #3 | 2 | 4 | exceeds normal capacity, incurs 2 penalty
Container #1 | 2 | 2 | container cannot be used
Put another way, I want to choose best container for the job that does not exceed normal capacity or incurs smallest penalty. Here is sample data and test:
WITH Containers(Name, CapacityNormal, CapacityMax) AS (
SELECT 'Container #1', 2, 2 UNION
SELECT 'Container #2', 2, 3 UNION
SELECT 'Container #3', 2, 4 UNION
SELECT 'Container #4', 3, 4 UNION
SELECT 'Container #5', 3, 5
), Tests(Quantity) AS (
SELECT 1 UNION
SELECT 2 UNION
SELECT 3 UNION
SELECT 4 UNION
SELECT 5 UNION
SELECT 6
)
SELECT CONCAT(Name, ' (', CapacityNormal, '/', CapacityMax, ')') AS Container, Quantity
FROM Containers
CROSS JOIN Tests
ORDER BY Quantity /* sort criteria goes here */