PDA

View Full Version : Làm thế nào để thêm cột số thứ tự



ham_tim_hieu
02-08-2004, 15:26
Giả sử trong Stored của SQL Server, tôi có 1 lệnh đơn giản sau
SELECT Ten,Diem FROM BangDiem WHERE Diem>=5 ORDER BY Diem
và tôi sẽ có kết quả là bảng điểm dạng
Tên | Điểm
AA | 8
BB | 7
CC | 6
Nay tôi muốn kết quả xuất ra có thêm 1 cột xếp thứ hạng hiện ra các chỉ số tăng tuần tự kiểu như
Tên | Điểm | Xếp hạng
AA | 8 | 1
BB | 7 | 2
CC | 6 | 3
Thì phải viết Stored như thế nào, nếu dùng Queries trong MS Access 2000 thì viết như thế nào?

oj_n
03-08-2004, 15:45
This is how you can do ranking in sql:

declare @tb table(ten char,diem int)
insert @tb select 'a',8
union all select 'b',7
union all select 'c',6
union all select 'd',5
union all select 'e',4


select *,(select count(*)+1 from @tb t2 where t2.diem>=t1.diem and t2.ten!=t1.ten)[xep hang]
from @tb t1
where t1.diem>5
order by diem desc

sontinh2004
06-08-2004, 23:43
I saw your posts. Great job OJ (simpson? :)).

Just a quick tip: In the future, there'll be a function, ROW_NUMBER(), that is included in SQL Server 2005 to overcome this challange ...
http://www.winnetmag.com/Article/ArticleID/42302/42302.html

Thx OJ.

oj_n
11-08-2004, 20:58
Neah, no Simpson here. ;)

Row_number() is just one of the many new functions that MS has implemented in Yukon, such Rank(), Dense_Rank(), and Ntile().

You can download Sql2k5 Express or Dev (if you have MSDN subscription) and take a look at book online for details.