PDA

View Full Version : Hiện số thứ tự row trong SQL



zhiivn
25-02-2004, 21:24
Các bạn cho mình hởi có cách nào thêm được một column chứa số thứ tự của khi mình query không? :)

Thai79
26-02-2004, 15:18
ban lam thế nầy nhé:
It is often desirable to have a row number on each row of a query result set. Unfortunately, T-SQL doesn't provide RowNum like you will find in Oracle. Here are a couple of methods for adding a row number column.

For small tables use a sub-query to count the rows up to and including the current row. An assumption is made that there is a primary key or unique index on the table.

--Assume the primary key is a composite of Col1 and Col2.
Select
RowNum=(Select Count(*) From TableName
Where Col1<=t1.Col1 And Col2 <=t1.Col2)
Col1, Col2, Col3, Col4
From TableName t1
Order By Col1, Col2

For larger tables it is usually faster to insert the rows selected into a temp table with an identity column, and then select from the temp table.

Create table #temp
(Col1 varchar(10),
Col2 varchar(10),
Col3 Int,
Col4 Decimal(12,2),
RowNum Int Identity)

Insert #temp(Col1, Col2, Col3, Col4)
Select Col1, Col2, Col3, Col4 From TableName
Order By Col1, Col2

Select RowNum, Col1, Col2, Col3, Col4
From #temp
Order By RowNum

Neither of these methods is very efficient but will provide a row number when needed. If you have another method that you prefer to use, please let me know. Any other comments or recommendations are welc

Thai79
26-02-2004, 15:25
hoac là:
Select
(Select Count(*) From customers
Where customerid<=t1.customerid )col1,companyname
From customers t1
Order By col1

thanhhung
27-02-2004, 17:06
Mình mới học CSDL thôi
Bạn nào có thể cho mình biết giữa Access và SQL khác nhau và giống nhau như thế nào !
Sẳn tiện thì bạn nào có thể giải thích giùm mình khóa chính, khóa lồng, khóa ngọai, và những quan hệ trong một CSDL?
Ai biết làm ơn mail về cho mình với
Cảm ơn trước nha!