Z
Z
zlogr2014-11-20 18:17:25
SQL
zlogr, 2014-11-20 18:17:25

How to sort by two fields as if it were one field?

The initial table table consists of two fields: list_price - the price of the product before the discount, sell_price - the price of the product, taking into account the discount.

+------------+-------------+
| list_price | sell_price  |
+------------+-------------+
| 8          |  4          |
| 10         |  5          |
| 7          |  3          |
| 0          |  12         |
| 0          |  42         |
+------------+-------------+

It is required to sort the goods so that the price before the discount is sorted in descending order along with the price with the discount (like list_price=sell_price if list_price is non-zero).
Desired sort result:
+------------+-------------+
| list_price | sell_price  |
+------------+-------------+
| 0          |  42         |
| 0          |  12         |
| 10         |  5          |
| 8          |  4          |
| 7          |  3          |
+------------+-------------+

If I just do a SELECT with ORDER BY, I get the following:
SELECT list_price, sell_price FROM table ORDER BY list_price DESC, sell_price DESC;
+------------+-------------+
| list_price | sell_price  |
+------------+-------------+
| 10         |  5          |
| 8          |  4          |
| 7          |  3          |
| 0          |  42         |
| 0          |  12         |
+------------+-------------+

Tell me please. It seems the task is simple, but I just don’t understand in which direction to google.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Sokolov, 2014-11-20
@sergiks

IF() will help:

SELECT 
  list_price,
  sell_price,
  IF( list_price=0, sell_price, list_price) AS orderme

FROM `_tmp_test`

ORDER BY orderme DESC

23bcdd6353e94f898313aebad2a06295.png

C
colzphml, 2014-11-20
@colzphml

The question is not entirely clear.
From what I understand, I can offer 2 options (sorry, but presented "as it should" does not explain how to sort):
1) SELECT list_price,sell_price FROM table ORDER BY sell_price DESC;
2) SELECT list_price,sell_price FROM table where list_price = '0' ORDER BY sell_price DESC
union
SELECT list_price,sell_price FROM table where list_price <> '0' ORDER BY sell_price DESC

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question