Tom Longworth
Tom Longworth

Reputation: 21

SQL count in a table

I'm looking to add some form of count function to my table, but am not quite sure how to do it. The table I have is:

First name Surname
Tom James
Mike James
Tom James
Mike Hamilton
William Morris
Mike James
Mike James

I would like it to have a count, of the full names that come up twice or more, like so:

First name Surname Count
Tom James 1
Mike James 1
Tom James 2
Mike Hamilton 1
William Morris 1
Mike James 2
Mike James 3

What is the best way to go about this in SQL? Unfortunately I need the result as per the table above, rather than simply:

First name Surname Count
Tom James 2
Mike James 3
Mike Hamilton 1
William Morris 1

Upvotes: 0

Views: 151

Answers (2)

Nida Fatima
Nida Fatima

Reputation: 9

I believe using group by on multiple columns would be a more appropriate approach to

select [first name], surname, COUNT(*) from Employee Group BY [first name], surname;

I believe using group by on multiple columns would be a more appropriate approach to

select [first name], surname, COUNT(*) from Employee Group BY [first name], surname;

Result:

enter image description here

Upvotes: 0

Moulitharan M
Moulitharan M

Reputation: 749

row_number function should work

select *,
row_number() over(partition by [first name],surname order by [first name]) as count 
from table_name

Upvotes: 2

Related Questions