简体   繁体   中英

How to get only the max row number row of record?

Below query results the record as follows ..

How to get only the max row number row of record? I have run this query for over 20,000 records to identify duplication and get the most recent date and its number of processed (RowNumber).

select [FileName], ProcessDate,
ROW_NUMBER() over (partition by [FileName] order by [FileName] desc) RowNumber 
from  StagingTable
where filename = 'abc.txt'

在此处输入图片说明

Are you looking for a filter?

select s.*
from (select [FileName], ProcessDate,
             ROW_NUMBER() over (partition by [FileName] order by ProcessDate desc) as RowNumber 
      from StagingTable
      where filename = 'abc.txt'
     ) s
where RowNumber = 1;

Note that the ORDER BY has changed.

If you want the total count as well, then add then in as an additional column:

select s.*
from (select [FileName], ProcessDate,
             count(*) over (partition by filename) as cnt,
             ROW_NUMBER() over (partition by [FileName] order by ProcessDate desc) as RowNumber 
      from StagingTable
      where filename = 'abc.txt'
     ) s
where RowNumber = 1;

Given your logic, there does not seem to be a maximum row number. Or is the row numbering tied to another field than ProcessDate ?

As far as I understand your problem, I would just use the following query:

SELECT [FileName], MAX([ProcessDate]) AS [ProcessDate], COUNT(*) AS [Count]
FROM [StagingTable]
GROUP BY [FileName]

Your query has an error: in the OrderBy you wrote FileName, but I guess you're using the date.

You can double on the ROW_NUMBER() columns:

WITH VersionSorting AS (
  select
    [FileName],
    ProcessDate,
    ROW_NUMBER() over (partition by [FileName] order by [ProcessDate] ASC) FileVersion,
    ROW_NUMBER() over (partition by [FileName] order by [ProcessDate] DESC) FileVersionInv
  from  StagingTable
)
SELECT FileName, ProcessDate, FileVersion
FROM VersionSorting
WHERE FileVersionInv = 1
-- AND FileName = 'abc.txt' 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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