Note that there are some explanatory texts on larger screens.

plurals
  1. PODeleting old records while keeping a minimum number of records per parent
    primarykey
    data
    text
    <p>My question is similar to <a href="https://stackoverflow.com/q/210515/66169">sql statement to delete records older than XXX as long as there are more than YY rows</a>, but that question just deals with a single parent, I want to delete records for all parents in one go.</p> <p>Consider this table:</p> <pre><code>CREATE TABLE Children ( ChildId int NOT NULL, ChildCreated datetime NOT NULL, ParentId int NOT NULL ) </code></pre> <p>This could be any parent-child relationship, so the names are generic. </p> <p>I would like to delete all children that are older than a month, but need to keep a minimum number of children for each parent regardless of their age.</p> <p>I tried some statements with nested SELECTs and GROUP BYs which gave me some results but none gave me the correct result set. </p> <p>Because I am using SQL Server I came up with the following solution that works great:</p> <pre><code>WITH CTE AS ( SELECT ROW_NUMBER() OVER (Partition BY ParentId ORDER BY ChildCreated DESC) As RowNo, ChildCreated FROM Children ) DELETE FROM CTE WHERE RowNo &gt; 10 AND RevisionCreated &lt; DATEADD(MONTH,-1,GetDate()) </code></pre> <p>The common table expression groups all children for each parent together and adds a continuous row number based on the creation order. The newest child for each parent has a row number of 1, the tenth newest has 10. So I can just delete all records with a row number greater 10 as long as they are also over a month old.</p> <p>My question is, what if I have to do the same thing on a system where CTEs are not supported. What is the <strong>ANSI SQL-92</strong> solution for this problem?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload