Share via

How to count specific data

Zaran 21 Reputation points
2022-02-16T19:34:41.623+00:00

Hi,

Could you please help me in the T_SQL code for the folowing sample?

I have a table (T1) with the following data:

ID, Name, Count


1,AA,0

1,AA,0,

1,BB,0

2,BB,0

2,AA,0

2,AA,0

2,BC,0

2,BC,0

2,CC,0

3,AA,0

3,BC,0

4,DD,0

5,AA,0

I nee to have the below result:

ID,Name,Count


1,AA,1

1,AA,1

1,BB,2

2,BB,1

2,AA,2

2,AA,2

2,BC,3

2,BC,3

2,CC,4

3,AA,1

3,BC,2

4,DD,1

5,AA,1

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.


1 answer

Sort by: Most helpful
  1. Naomi Nosonovsky 8,906 Reputation points
    2022-02-16T20:03:15.873+00:00

    ;with cteResult as (select ID, Name, DENSE_RANK() over (partion by ID order by name) as Count from @t)
    select * from cteResult order by ID, Name

    The only problem is that it would not be exactly the same result as you shown.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.