sql assign a category id when using order by
I'm new to SQL.
When I order by SomeData on my table I get:
ID SomeData
6 ABC
3 ABC
12 FG
1 FH
2 GI
4 JU
8 K3
5 K3
11 P7
great. but what i really want on output is
ID Category
6 1
3 1
12 2
1 开发者_如何学JAVA 3
2 4
4 5
8 6
5 6
11 7
That is every time SomeData changes on the sort I want to increment Category by one
I can't see how to do this. Any help would be greatly appreciated. Thanks.
If you are on SQL-Server, you can use the DENSE_RANK()
ranking function in combination with OVER
:
SELECT ID
, DENSE_RANK() OVER (ORDER BY SomeData)
AS Category
FROM myTable
ORDER BY SomeData
See: SQL-Server: Ranking Functions
SELECT ROW_NUMBER() OVER(ORDER BY SomeData ASC) AS Category, otherfield1..
精彩评论