简体   繁体   English

查询后如何查找行?

[英]How to find row after query?

I have a query, and I need to find the row number that the query return the answer. 我有一个查询,我需要找到查询返回答案的行号。 I do not have a counter field. 我没有柜台领域。 How do I do it? 我该怎么做?

Thanks in advance. 提前致谢。

SELECT 
  ROW_NUMBER() OVER (<your_id_field_here> ORDER BY <field_here>) as RowNum,
  <the_rest_of_your_fields_here>
FROM
  <my_table>

If you have a primary key, you can use this method on SQL Server 2005 and up: 如果您有主键,则可以在SQL Server 2005及更高版本上使用此方法:

SELECT 
  ROW_NUMBER() OVER (ORDER BY PrimaryKeyField) as RowNumber,
  Field1,
  Field2
FROM
  YourSourceTable

If you don't have a primary key, what you may have to do is duplicate your table into a mermory table (or a temp table if it is very large) using a method like this: 如果没有主键,则可能需要使用以下方法将表复制到内存表(或临时表(如果非常大)中):

DECLARE @NewTable table (
    RowNumber BIGINT IDENTITY(1,1) PRIMARY KEY,
    Field1 varchar(50),
    Field2 varchar(50),
)

INSERT INTO @NewTable
    (Field1, Field2)
SELECT
    Field1,
    Field2
FROM
    YourSourceTable

SELECT
    RowNumber,
    Field1,
    Field2
FROM
    @NewTable

The nice part about this, is that you will be able to detect identical rows if your source table does not have a primary key. 这样做的好处是,如果源表没有主键,您将能够检测到相同的行。

Also, at this point, I would suggest adding a primary key to every table you have, if they don't already have one. 另外,在这一点上,我建议向您拥有的每个表添加一个主键(如果还没有的话)。

create table t1 (N1 int ,N2 int) 创建表t1(N1 int,N2 int)

insert into t1 select 200,300 插入t1选择200,300

insert into t1 select 200,300 插入t1选择200,300

insert into t1 select 300,400 插入t1选择300,400

insert into t1 select 400,400 ..... ...... 插入t1中,选择400,400 ..... ......

select row_number() over (order by [N1]) RowNumber,* from t1 从(t1)开始选择(按[N1]顺序)行号*

I have a Query, and I need to find the row number that the query return the answer. 我有一个查询,我需要找到查询返回答案的行号。 I do not have any counter field. 我没有任何计数器字段。 how I do it ? 我该怎么做?

If I understand your question correctly, you have some sort of query that returns a row, or a few rows (answer, answers) and you want to have a row number associates with an "answer" 如果我正确理解了您的问题,则您有某种查询会返回一行或几行(答案,答案),并且您希望将行号与“答案”相关联

As you said you do not have any counter field so what you need to to is the following: 如您所说,您没有任何计数器字段,因此需要执行以下操作:

  • decide on the ordering criteria 决定订购标准
  • add the counter 添加计数器
  • run the query 运行查询

It would really help if you provided more details to your question(s). 如果您为问题提供了更多详细信息,那将真的有帮助。 If you confirm that I understand your question correctly, I will add a code example 如果您确认我正确理解了您的问题,我将添加一个代码示例

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

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