I have a table of products, and I need to write an SQL query which orders these products alphabetically according to their manufacturer.
i.e.
SELECT * FROM ProductsTable ORDER BY Manufacturer
But the complication is that we are trying to promote one particular manufacturer. So all the products for this manufacturer need to come at the top and not be alphabetised with the rest.
e.g.
+---------+------------+
|Product |Manufacturer|
+---------+------------+
|pears |Jim |
|apples |Fred |
|tomatoes |Adam |
|oranges |Bob |
|bananas |Fred |
|grapes |Carl |
+---------+------------+
If we are promoting Fred, the query would result in
+---------+------------+
|Product |Manufacturer|
+---------+------------+
|apples |Fred |
|bananas |Fred |
|tomatoes |Adam |
|oranges |Bob |
|grapes |Carl |
|pears |Jim |
+---------+------------+
Is there a way to do this?
Try:
SELECT *, CASE WHEN Manufacturer = 'Fred' THEN 0 ELSE 1 END AS Ordering
FROM ProductsTable
ORDER BY Ordering, Manufacturer
Next to manufacturer, put a new field: Weight, and give weight 1 to promoting manufacturer, and 0 to others, then write your query:
SELECT * FROM ProductsTable ORDER BY Weight, Manufacturer
to promote manufacturer Fred, use:
UPDATE ProductsTable SET Weight = 0;
UPDATE ProductsTable SET Weight = 1 WHERE Manufacturer='Fred';
(it would be good to wrap those two update queries into transaction)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With