简体   繁体   English

向 SQL 查询的结果集添加行号

[英]Add a row number to result set of a SQL query

I have a simple select statement.我有一个简单的选择语句。 I want to add a temporary column which will number the rows in my result set.我想添加一个临时列,它将为我的结果集中的行编号。 I tried this -我试过这个 -

declare @num int
set @num = 0;
select t.A, t.B, t.C, (@count + 1) as number
from tableZ as t

It assigns the 1 to all rows.它将 1 分配给所有行。 I tried @count = @count + 1 and it did not work.我试过@count = @count + 1 但它没有用。 How do I do this thing in a simple manner ?我如何以简单的方式做这件事?

thanks.谢谢。

SELECT
    t.A,
    t.B,
    t.C,
    ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS number
FROM tableZ AS t

See working example at SQLFiddle请参阅SQLFiddle 的工作示例

Of course, you may want to define the row-numbering order – if so, just swap OVER (ORDER BY (SELECT 1)) for, eg, OVER (ORDER BY tC) , like in a normal ORDER BY clause.当然,您可能想要定义行编号顺序——如果是这样,只需将OVER (ORDER BY (SELECT 1))交换为例如OVER (ORDER BY tC) ,就像在正常的ORDER BY子句中一样。

The typical pattern would be as follows, but you need to actually define how the ordering should be applied (since a table is, by definition, an unordered bag of rows):典型的模式如下,但您需要实际定义应如何应用排序(因为根据定义,表是一个无序的行袋):

SELECT t.A, t.B, t.C, number = ROW_NUMBER() OVER (ORDER BY t.A)
  FROM dbo.tableZ AS t
  ORDER BY t.A;

Not sure what the variables in your question are supposed to represent (they don't match).不确定您问题中的变量应该代表什么(它们不匹配)。

So before MySQL 8.0 there is no ROW_NUMBER() function.所以在 MySQL 8.0 之前没有 ROW_NUMBER() 函数。 Accpted answer rewritten to support older versions of MySQL: Accpted 答案重写以支持旧版本的 MySQL:

SET @row_number = 0;
SELECT t.A, t.B, t.C, (@row_number:=@row_number + 1) AS number
FROM dbo.tableZ AS t ORDER BY t.A;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM