3

i have a table like this :

key   value   rating

1      1       1

0      0       3

0      1       2

First i want to order the table by rating column in descending order and for those rows where value column is 1 , it should be ordered by key in descending order. So the resulting table has to be like this:

key   value   rating

0      0       3

1      1       1

0      1       2

i have tried this :

SELECT * FROM `table` ORDER BY CASE `value` WHEN 1 THEN `key` 
        END 
 `table`.`pair` desc
3
  • 1
    What should happen if there's another record with value=0 and rating=2? Commented Jan 28, 2015 at 7:12
  • @default locale : actually the third column is a date time field in my real table. so the values in the third column will be unique. i have changed the column names for this question Commented Jan 28, 2015 at 7:15
  • well, you can substitute numbers back to corresponding dates :) My question is: if you have non-special value with rating equal to special value which record should go first? Commented Jan 28, 2015 at 7:17

2 Answers 2

2

You didn't specify how records with value=1 and value<>1 should be ordered in respect to each other. So, I'll guess that value=1 records will come last:

SELECT *
FROM table
ORDER BY
    (
    CASE
        WHEN value=1 THEN -1
        ELSE rating
    END
    ) desc,
    key desc

If you have negative ratings you can replace -1 with your negative limit. The goal is to sort value=1 records separately.

Check out this fiddle. I added some records to illustrate issues in the problem statement.

Currently it's unclear from your question how records like (0,1,4), (1,1,2) and (0,0,3) should be ordered.

Sign up to request clarification or add additional context in comments.

2 Comments

when i run this query, i am getting {0,0,3}, {0,1,2}, {1,1,1}. So its ordered by rating . but its not ordered by key in descending order
Please check out the updated question. First time, I forgot key desc, but now it should work.
1

Try this order by. Use case statement to custom the sort order

SELECT *
FROM   yourtable
ORDER  BY CASE
            WHEN value = 0 THEN rating
            ELSE key
          END DESC 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.