开发者

SQL: Add counters in select

开发者 https://www.devze.com 2023-01-02 07:37 出处:网络
I have 开发者_StackOverflowa table which contains names: Name ---- John Smith John Smith Sam Wood George Wright

I have 开发者_StackOverflowa table which contains names:

Name
----
John Smith
John Smith
Sam Wood
George Wright
John Smith
Sam Wood

I want to create a select statement which shows this:

Name

'John Smith 1'

'John Smith 2'

'Sam Wood 1'

'George Wright 1'

'John Smith 3'

'Sam Wood 2'

In other words, I want to add separate counters to each name. Is there a way to do it without using cursors?


Use ROW_NUMBER():

SELECT Name, ROW_NUMBER() OVER(Partition BY Name ORDER BY Name) as [Rank]
FROM MyTable


Doing:

select name, count(*) as total from table group by name;

will get you something that looks like this:

name         |  total
-------------+------------
John Smith   |  2
-------------+------------
Sam Wood     |  2
-------------+------------
George Wright|  1

This isn't what you really wanted though - ROW_NUMBER(), as ck pointed out, is what you want, but not all databases support it - mysql doesn't, for example. If you're using MySQL, this might help: ROW_NUMBER() in MySQL

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号