SQL:在选择中添加计数器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2965489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 06:27:00  来源:igfitidea点击:

SQL: Add counters in select

sqlcounter

提问by etarvt

I have a 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:

我想创建一个 select 语句来显示这个:

Name

姓名

'John Smith 1'

'约翰史密斯 1'

'John Smith 2'

《约翰·史密斯 2》

'Sam Wood 1'

'山姆伍德 1'

'George Wright 1'

'乔治赖特 1'

'John Smith 3'

《约翰·史密斯 3》

'Sam Wood 2'

《山姆伍德 2》

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

换句话说,我想为每个名称添加单独的计数器。有没有办法在不使用游标的情况下做到这一点?

采纳答案by cjk

Use ROW_NUMBER():

使用 ROW_NUMBER():

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

回答by Duncan Lock

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

虽然这不是您真正想要的 - 正如 ck 指出的那样,ROW_NUMBER() 是您想要的,但并非所有数据库都支持它 - 例如,mysql 不支持。如果您使用的是 MySQL,这可能会有所帮助: MySQL 中的 ROW_NUMBER()