Sanchit Saxena
Sanchit Saxena

Reputation: 171

SQL sorting such that rows are sorted only where another column value is equal

I have a SQL query problem. So here is a table which is a result of a large query.

+---------+-------------+------------+ | page_id | TotalDegree | matchCount | +---------+-------------+------------+ | 116 | 7.0000 | 4 | | 142 | 3.0000 | 4 | | 109 | 4.0000 | 2 | | 119 | 4.0000 | 2 | | 108 | 2.0000 | 2 | | 132 | 4.0000 | 1 | | 133 | 9.0000 | 1 | | 146 | 9.0000 | 1 | | 114 | 4.0000 | 1 | | 125 | 9.0000 | 1 | | 113 | 1.0000 | 1 | | 127 | 9.0000 | 1 | | 120 | 4.0000 | 1 | | 129 | 9.0000 | 1 | | 121 | 9.0000 | 1 | +---------+-------------+------------+ 15 rows in set (0.00 sec)

Now I want to sort a table on the basis of 'TotalDegree' in ascending order such that sorting should be done internally where the 'matchCount' column value is same. Example: The first two rows has 'matchCount' value 4 so sorting should be done in between these two rows on the basis of 'TotalDegree' in ascending order. Similarly, all the rows with 'matchCount' equals to 1 should be sorted amongst themselves. So the sorted table should look like as below.

+---------+-------------+------------+ | page_id | TotalDegree | matchCount | +---------+-------------+------------+ | 142 | 3.0000 | 4 | | 116 | 7.0000 | 4 | | 108 | 2.0000 | 2 | | 109 | 4.0000 | 2 | | 119 | 4.0000 | 2 | | 113 | 1.0000 | 1 | | 132 | 4.0000 | 1 | | 114 | 4.0000 | 1 | | 120 | 4.0000 | 1 | | 133 | 9.0000 | 1 | | 146 | 9.0000 | 1 | | 125 | 9.0000 | 1 | | 127 | 9.0000 | 1 | | 129 | 9.0000 | 1 | | 121 | 9.0000 | 1 | +---------+-------------+------------+
How can such a query can be designed ? Thanks in advance.

Upvotes: 1

Views: 70

Answers (2)

peter.petrov
peter.petrov

Reputation: 39477

You want to sort on MatchCount first (in descending order),
then on TotalDegree (in ascending order).

select * from TableName  
order by MatchCount desc, TotalDegree asc;

Upvotes: 1

SQL.injection
SQL.injection

Reputation: 2647

Have a look at the order by clause

select * from fooTable order by foo1 desc, foo2 asc

in your case:

select  page_id ,TotalDegree , matchCount  from fooFable order by matchCount  desc, TotalDegree asc

Upvotes: 0

Related Questions