简体   繁体   中英

Ordering an SQL query with exceptions

I have a table of products, and I need to write an SQL query which orders these products alphabetically according to their manufacturer.

ie

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)

这样的事情应该基于我对Microsoft Access数据库的经验,但我希望在其他一些SQL数据库中工作...

SELECT * FROM ProductsTable ORDER BY (Manufacturer='Fred'), Manufacturer;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM