向 SQL 查询的结果集添加行号 [英] Add a row number to result set of a SQL query

查看:93
本文介绍了向 SQL 查询的结果集添加行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的选择语句.我想添加一个临时列,它将为我的结果集中的行编号.我试过这个 -

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

它将 1 分配给所有行.我试过@count = @count + 1 但它没有用.我如何以简单的方式做这件事?

It assigns the 1 to all rows. I tried @count = @count + 1 and it did not work. How do I do this thing in a simple manner ?

谢谢.

推荐答案

典型的模式如下,但您需要实际定义应该如何应用排序(因为根据定义,表是一个无序的包行):

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).

这篇关于向 SQL 查询的结果集添加行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆