Delete all by last 10 records...

I have a table where I only want to keep the last 10 records of the of the product.
say for instance, I have a products table and it has apples, oranges... and another table that lists each sales transaction for each product.  As you can see.. you would get 1000's of records in the sales table.
I want to delete all records in the sales table, except for the last 10 records for apples?
any help?

I have a table where I only want to keep the last 10 records of the of the product.
TRUNCATE TABLE is faster than DELETE and uses fewer system and transaction log resources.
Try
-- code #1 v2
IF Object_ID('tempdb..#LastSales','U') is not null DROP TABLE #LastSales;
;with
SalesSeq as (
SELECT *, Seq= row_number() over (partition by IDProd order by SalesDate desc)
  from Sales
SELECT IDSales, IDProd, SalesDate, Qty
  into #LastSales
  from SalesSeq
  where Seq <= 10;
TRUNCATE TABLE Sales;
INSERT into Sales (IDSales, IDProd, SalesDate, Qty)
SELECT IDSales, IDProd, SalesDate, Qty
from #LastSales;
IF Object_ID('tempdb..#LastSales','U') is not null DROP TABLE #LastSales;
You cannot use TRUNCATE TABLE on tables that:
    Are referenced by a FOREIGN KEY constraint
    Participate in an indexed view
    Are published by using transactional replication or merge replication.
To test:
CREATE TABLE Products (IDProd int primary key, DescProd varchar(30));
CREATE TABLE Sales (IDSales int primary key, IDProd int references Products, SalesDate smalldatetime, Qty smallint);
INSERT into Products values
(1, 'apple'), (2, 'orange');
INSERT into Sales values
(1, 1, '20120103', 18), (2, 1, '20120104', 22), (3, 1, '20120105', 50),
(4, 1, '20120105', 19), (5, 2, '20120103', 5), (6, 1, '20120113', 5),
(7, 1, '20120123', 20), (8, 1, '20120203', 7), (9, 1, '20120203', 20),
(10, 1, '20120303', 21), (11, 1, '20120313', 2), (12, 1, '20120401', 15);
José Diz     Belo Horizonte, MG - Brasil

Similar Messages

  • JDBC Scenario: Delete all the existing records and Insert

    Dear All,
    Scenario: IDoc to JDBC
    PI need to delete all the existing records in the SQL table then need to insert the records.I have created a two statements in the target structure.
    Statement1
       -> TableName
           -> action : DELETE
           -> Table : TableName
    Statement2
       -> TableName
           -> action : INSERT
           -> Table : TableName
           ->Access
               -> Elements
    I am getting below error while try to delete the records in the table.
    JDBC message processing failed; reason Error processing request in sax parser: Error when executing statement for  table/stored proc. 'Tablename' (structure 'Statement1'): java.sql.SQLException: FATAL ERROR document format: structure 'Statement1', no key element found
    Note: we use above structure in the another interface without specifying any Key for Delete operation(Server is same but different database for this two interface) and it works fine. Although the Primary keys has been set in the SQL table i am getting the above error.
    let me know what are the setting need to make in PI and SQL DB to achieve this.
    Regards,
    Manikandan Shanmugam
    Edited by: Manikandan Shanmugam on Nov 8, 2011 6:19 AM

    The straucture what you have deined for Delete is not correct, you should have key field in statement structure then only you can perform Delete operation.
    refer below link
    http://help.sap.com/saphelp_nwpi71/helpdata/EN/44/7b6e85fde93673e10000000a114a6b/content.htm
    Regards,
    Raj

  • Deleting all the similar records except one

    I have a table without a primary/unique key, this table contains too many rows that have the same column values(the row is duplicated), How can I delete all the duplicated rows and keep one copy of this rows?

    <BLOCKQUOTE><font size="1" face="Verdana, Arial, Helvetica">quote:</font><HR>Originally posted by Waleed Dallah ([email protected]):
    I have a table without a primary/unique key, this table contains too many rows that have the same column values(the row is duplicated), How can I delete all the duplicated rows and keep one copy of this rows?<HR></BLOCKQUOTE>
    Hi
    This query may be solev ur problem
    delete table where rowid not in(select min(rowid) from table1 group by fieldname)
    This query if u want to keep latest row use max(rowid) instead of min(rowid)
    let me know
    by
    venkat
    ([email protected])

  • How to delete all the data records

    Hi,
    After testing and updating the task hiyerarcies, How can I delete the all condolidation records from cubes, ods, etc. easily. In order to start a clean UCMON, i need a your suggestions.
    thanks,
    Yigit

    Hi Dan;
    I can't  see this option... and i have set up the Tools view (Edit > settings > Workbench > Main Navigation > Views select Tools) > Transaction Data > Analyze and Repair Data Streams.
    Please check this out:
    where i see this??
    Thanks!
    César.

  • Best way to delete large number of records but not interfere with tlog backups on a schedule

    Ive inherited a system with multiple databases and there are db and tlog backups that run on schedules.  There is a list of tables that need a lot of records purged from them.  What would be a good approach to use for deleting the old records?
    Ive been digging through old posts, reading best practices etc, but still not sure the best way to attack it.
    Approach #1
    A one-time delete that did everything.  Delete all the old records, in batches of say 50,000 at a time.
    After each run through all the tables for that DB, execute a tlog backup.
    Approach #2
    Create a job that does a similar process as above, except dont loop.  Only do the batch once.  Have the job scheduled to start say on the half hour, assuming the tlog backups run every hour.
    Note:
    Some of these (well, most) are going to have relations on them.

    Hi shiftbit,
    According to your description, in my opinion, the type of this question is changed to discussion. It will be better and 
    more experts will focus on this issue and assist you. When delete large number of records from tables, you can use bulk deletions that it would not make the transaction log growing and runing out of disk space. You can
    take the table offline for maintenance, a complete reorganization is always best because it does the delete and places the table back into a pristine state. 
    For more information about deleting a large number of records without affecting the transaction log.
    http://www.virtualobjectives.com.au/sqlserver/deleting_records_from_a_large_table.htm
    Hope it can help.
    Regards,
    Sofiya Li
    Sofiya Li
    TechNet Community Support

  • Form wont delete the last record

    Hi All
    I have the follwoing Form
    e.g
    First_name || Last_name || Emp_id
    The Forms works ok when populating the form and saves,you can delete all the records except for the last record if you delete the last record it's save.
    Does anyone whan what could be the problem.
    please help i'm new to Forms.

    you can delete all the records except for the last record if you delete the last record it's saveSo, can or cannot you delete the last record?
    What do you mean with "it´s save"?

  • Recently, U2 music appeared on my ipod without my requesting it or wanting it. I was able to delete all of the songs except for one. How do I delete the last one from my ipod? The song does not show up in iTunes when I plug my ipod into the computer.

    Recently, U2 music appeared on my ipod without my requesting it or wanting it. I was able to delete all of the songs except for one. How do I delete the last one from my ipod? The song does not show up in iTunes when I plug my ipod into the computer. The version installed on my ipod is 7.1.2(11D257).

    Hi donfrommars,
    Welcome to the Apple Support Communities!
    Please use the following article for information and instruction on deleting the U2 album from your devices and account.
    Remove iTunes gift album "Songs of Innocence" from your iTunes music library and purchases
    Have a great day,
    Joe

  • HT1766 If I restore my new iphone from my last backup will it delete all of the new things that i have on my phone

    If i restore my new iphone from my last backup will it delete all of the new content that I currently have on my phone? would it be better off to set it up as a new iphone? and if i set it up as a new iphone what will that do?

    If you restore from your last backup, it will replace what you now have on your phone. If you set it up as new, you will have a phone just out of the box without any of your data on it. You can download any apps again. You can sync your music through iTunes.

  • HT1414 I have changed my Iphone once last year. My iphone has being playing up for the best part of 6 months. It Keeps deleting all my music of the phone. it freezes and will not allow me to turn it on or off. if i am in the middle of an app it will rando

    I have changed my Iphone once last year. My iphone has being playing up for the best part of 6 months. It Keeps deleting all my music of the phone. it freezes and will not allow me to turn it on or off. if i am in the middle of an app it will randomly shut it down and turn the phone off totally (even if it is charged.) It will not charge properly, it has to be in a exact position to charge and even then go's off and on. I thought this my be my charger but the charger works fine on another phone. it will not allow texts to come through properly and sometimes will not not let me ring people it just freezes and i have to turn it off and on a couple of times in order for it to work. it will not let me update apps and the silent button is not silent it still go's of on ringer.The keyboard will freeze up not allowing me to type anything.  It wants me to pay £126.44 for it to be repaire when i have nothing to do with why its not working!

    That is correct.
    That is the price of a replacement iphone once your iphone is outside of the warranty period

  • Last iTunes update 10.2.2.12 deleted all music files and all artwork

    Within the last month I got a notice to upgrade Apple iTunes and Quicktime software which I did not thinking anything about it.  I have used myiPod since then but not in iTunes at all and no synching.  I have about 225 CD's loaded in iTunes plus some other music from Home Sharing that my son/daughter bought with our account in the iTunes store.  I recently got a new double CD requested for my birthday and decided to load it into iTunes and on my computer.  It had problems automatically recognizing the CD so I checked all the settings and they were correct rebooted my computer and one CD loaded not the other and had to reboot again to get the second to load.  But also I noticed ALL ALBUM ARTWORK was gone.  Both the album artwork I got from Apple and the Album artwork I loaded (the bulk of my CD's are older CD's so the Apple iTunes store does not have the artwork typically) was missing.  I thought that was a little odd but iTunes has done this before after updates but usually ONLY with the album artwork I loaded being missing.  In any case I tried Get Artwork via the iTunes sote and got error messages that Album artwork could not load.  I also then tried to load the artwork manually and iTunes music library rejected it.  Then I tried to play a song listed.  It said the song is not there.  Now all of my music is listed in my iTunes library, but apparently NONE of it is actually there.  I go to where iTuens Music Library and sure enough only the last 4 CD's are there.  Apparently the last Apple Update deleted all the music files, and all the artwork with it, yet still lists them in iTunes but they are nowhere to be found.  Before I go into my backup files on an external hard drive, it appears others are having this issue too, and I am wondering if anyone has actually got a simple fix from Apple or not.  . 

    Follow up - I could not locate any of the files on my "c" drive of my laptop.  Realizing that I am gonna probably have to reload everything from my external hard drive backup I went ahead and just started the process.  I uninstalled and reinstalled iTunes software, which turned out to NOT be required at all as when I reopened iTunes all of the music files were again listed just as before but none of them were actually there or the artwork.  I then copied all the music files/folders over into the iTunes music folder and about 90% of them then showed up with about 98% of the artwork.  The other 10% just had to be matched up as the music was there but iTunes was not looking in the right location for it now, most likely different folder names.  So after about 6 hours I am back to having everything back on the computer and reorganized again.  I am now going to back up again (in multiple locations - 2 hard drives and I may add a flash drive backup too) and then do the inevitable scary Apple sync.  I find it funny that with other company's software that syncs, it actually syncs, where Apple sync software seems to look for items to delete from one source or the other during its sync. They really should rename it because it is not a true "sync".  In any case I was happy and surprised to find that about 98% of the artwork came through with the music which never used to happen in the past, so that saved a lot of time to say the least.  To anyone who ever does anything with Apple or Windows software updates, all I can say from years of experience now is backup, backup, backup, and backup prior to updating. 

  • Delete all record in a table, the insert speed is not change.

    I have an empty table, and i insert a record need 100ms,
    when this table has 40,0000 record, i insert a record need 1s, this is ok, because i need do a compare based an index before insert a record, so more record, need more time.
    The problem is when i delete all record in this table, the insert time is still 1s, not reduce to 100ms.Why?

    Hello,
    Read through this portion of oracle documentation
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14220/logical.htm#CNCPT004
    The reason is still taking 1s, because when you inserted 400K record because HWM (The high water mark is the boundary between used and unused space in a segment.) moved up. And when you deleted all the records your HWM still at the same marker and didn't get to reset to 0. So when you insert 1 record it lookings for free space and after finding (generally a regular inserts got 6 steps it inserts data). If you truncate your table you and try it again it will be faster as your HWM is reset to 0.
    Regards

  • Delete last record in plsql table

    TYPE r_LOOPElement IS RECORD (TermID   NUMBER
    TYPE t_LOOPType IS TABLE OF r_LOOPElement INDEX BY BINARY_INTEGER;
    i_CustomerLoop      t_LOOPType ;
    i_CustomerLoop(1).TermID=1;
    i_CustomerLoop(2).TermID=2;
    i_CustomerLoop(3).TermID=3;based on some conditions, i need to delete the last record from i_CustomerLoop
    whichi s the best way to do it. because i will sometimes have duplicate values for TermID in this plsql table.

    Hi,
    See [Deleting Collection Elements (DELETE Method)|http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28370/collections.htm#CJAFGFIG]
    Regards,

  • Yesterday I was able to take photos but around 9pm last night my rear camera stop working. I have reseted my phone and have also restored it and the camera still is not working. Also I have deleted all apps that can have access to the camera.

    Yesterday I was able to take photos but around 9pm last night my rear camera stop working. I have reseted my phone and have also restored it and the camera still is not working. Also I have deleted all apps that can have access to the camera and i have updated the new IOS.What else should I do ? Is this a hardware problem?

    Looks like a hardware issue that will have to be taken to a store

  • Error 'Domain already exists. Delete all records'

    Hello, I am having an issue with transferring my domain name. Keep getting the error 'Domain already exists. Delete all records'.  I assume this needs some kind of cashe flush but not quite sure how to do it!
    Any help would be appriciated,
    Thanks,
    Callum

    Hi Callum,
    What is the domain name and to what site are you trying to add it to?
    Regards,
    Aish

  • Is it possible to Delete all Records of Std. SAP tables for Quality Server

    Hi,
    We want to delete some sensetive information from Test(Quality) Server.
    For Std. SAP tables, is it possible to delete all Records?

    Hi, Through an ABAP program it is possible. You can develop the custom program on Development server than transfer it to QS and run the program.
    Regards,
    Aalok
    Edited by: aalokg on May 13, 2010 12:19 PM

Maybe you are looking for