Results 1 to 7 of 7
  1. #1
    Join Date
    Jan 2003
    Location
    Atlanta
    Posts
    134

    Red face Unanswered: Oracle SQL - Need help to delete records from a table

    I have a table xyz(user char(10),dateofentry datetime) and I have data like

    user1, '08/10/2010 10:00:01'
    user1, '08/10/2010 09:00:01'
    user1, '08/10/2009 14:00:01'
    user2, '08/09/2010 10:00:01'
    user2, '07/09/2010 10:00:01'

    I want to keep 2 records for each user and delete all other greater than 2 in number for each user. Can anyone help how can I do it?

    The result that remains in table would be like:
    user1, '08/10/2010 10:00:01'
    user1, '08/10/2010 09:00:01'

    user2, '08/09/2010 10:00:01'
    user2, '07/09/2010 10:00:01'

    Any help is appreaciated.

  2. #2
    Join Date
    Aug 2003
    Location
    Where the Surf Meets the Turf @Del Mar, CA
    Posts
    7,776
    Provided Answers: 1
    post SELECT that report records you desire to keep
    You can lead some folks to knowledge, but you can not make them think.
    The average person thinks he's above average!
    For most folks, they don't know, what they don't know.
    Good judgement comes from experience. Experience comes from bad judgement.

  3. #3
    Join Date
    Aug 2009
    Location
    Olympia, WA
    Posts
    337
    Code:
    DELETE FROM xyz
    WHERE (xyz.user, xyz.dateofentry) IN (
      SELECT user, dateofentry
      FROM (
        SELECT user, dateofentry, lag(dateofentry, 2) 
          OVER (PARTITION BY user ORDER BY dateofentry) AS del_me
        FROM xyz
      ) sub
      WHERE sub.del_me IS NOT NULL
    )

  4. #4
    Join Date
    Jan 2003
    Location
    Atlanta
    Posts
    134

    Thanks for your script.

    I will try it but many thanks

  5. #5
    Join Date
    Jul 2003
    Posts
    2,296
    yeah, you really didn't specify the RULE that would determine the ORDER per set.
    are we supposed to guess? i suppose we are guessing it is by dateofentry descending?
    - The_Duck
    you can lead someone to something but they will never learn anything ...

  6. #6
    Join Date
    Jul 2003
    Posts
    2,296
    [double post]
    - The_Duck
    you can lead someone to something but they will never learn anything ...

  7. #7
    Join Date
    Aug 2009
    Location
    Olympia, WA
    Posts
    337
    > i suppose we are guessing it is by dateofentry descending?

    That was my guess based on which row was dropped in the example. But if we waited for posters to provide all of the details they are supposed to we'd never solve anyone's problems.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •