Home Forums SQL Server 2005 T-SQL (SS2K5) Help with sql statement to delete old records for user if multiple records found RE: Help with sql statement to delete old records for user if multiple records found

  • I took a few liberties and created my own version of your data. I made the assumption that LastUpdated is a datetime datatype. If it is not, it will need to converted to a datetime because you can't count on string values sorting the way you think they should with the dateformat you posted.

    Notice that the first thing is a consumable table with data. This is what I meant by my first post.

    if OBJECT_ID('tempdb..#UserSession') is not null

    drop table #UserSession

    create table #UserSession

    (

    UserName varchar(25),

    LastUpdated datetime,

    SessionID char(6)

    )

    insert #UserSession

    select 'User1', '2013-01-01 10:00:00.000', 'SESS01' union all

    select 'User1', '2013-01-01 11:00:00.000', 'SESS02' union all

    select 'User1', '2013-01-01 12:00:00.000', 'SESS03' union all

    select 'User2', '2013-01-01 10:00:00.000', 'SESS04' union all

    select 'User3', '2013-01-01 10:00:00.000', 'SESS05' union all

    select 'User3', '2013-01-01 11:00:00.000', 'SESS06';

    --Use ROW_NUMBER to isolate the most current values for each UserName.

    --The most current row will have a RowNum of 1

    with myCTE as

    (

    select UserName,

    LastUpdated,

    SessionID,

    ROW_NUMBER() over (PARTITION BY UserName order by LastUpdated desc) as RowNum

    from #UserSession

    )

    --Now we can use the cte as our driver for deleting.

    delete myCTE where RowNum > 1

    select * from #UserSession

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/