3

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       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.

3

2 Answers 2

3

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

0
2
SELECT ROW_NUMBER() OVER(ORDER BY SomeData ASC) AS Category, otherfield1..
2
  • 1
    ROW_NUMBER() seems to just assign 1,2,...7 to each row
    – mac
    Jun 22, 2011 at 17:46
  • seems to me that this is somewhat like subtotalling on a report when the month changes during a sort.
    – mac
    Jun 22, 2011 at 17:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.