Optimus
Optimus

Reputation: 93

Order by grouping in SQL Server

How can I order the point column based on the grouping of attributes?

For example:

   degreeid   studentid    point
     1          1           100
     2          1           150
     3          1           205 
     4          1           600
     1          2           520
     2          2           566
     3          2           450
     4          2           566
     5          2           450
     ......
     1          n           m

I want to to show the query result in this way:

  degreeid     studentid      point
       1            2           520
       1            1           100
       1            n           90       --( min value)
       2            2           566
       2            1           150
       2            n           70       --( min value)

I used cursor, for each degreeid make

ORDER point DESC

and the result

INSERT INTO #temporary TABLE

This temporary table used to show data.

Is this a good way, because I have a lot of data, about 500'000 records?

Upvotes: 0

Views: 711

Answers (2)

vercelli
vercelli

Reputation: 4757

Without your query is hard to know but I guess you want to order with 2 criteria:

select degreeid   ,studentid    ,point
  from table
order by degreeid   , point desc

If you are grouping the order by is the same:

select degreeid   ,studentid    ,sum(point) as sum_point
  from table
 group by degreeid   ,studentid
order by degreeid   , sum_point desc

Upvotes: 1

Mahesh Madushanka
Mahesh Madushanka

Reputation: 2988

USE ORDER BY IN FOLLOWING FORMAT

SELECT * FROM TABLE ORDER BY degreeid ASC,point DESC;

example

mysql> SELECT user,duration FROM tt order by USER ASC,duration DESC;
+--------+----------+
| user   | duration |
+--------+----------+
| user1  | 00:06:00 |
| user1  | 00:02:00 |
| user2  | 00:06:00 |
| user2  | 00:01:00 |
| user3  | 00:04:00 |
| user55 | 00:01:00 |
| user55 | 00:01:00 |
+--------+----------+
7 rows in set (0.00 sec)

Upvotes: 1

Related Questions