Note that there are some explanatory texts on larger screens.

plurals
  1. POconditionally merge and aggregate adjacent rows in T-SQL
    primarykey
    data
    text
    <p>I have a 100K-row table representing sales during a particular time period. Usually the periods are at least a few hours long, but occasionally we get a period that's only a few minutes long. These tiny periods mess up downstream reporting, so I'd like to merge them with the preceding period. Any period that's 30 minutes or less should get merged with the previous period, with sales data summed across periods. There may be zero, one, or many multiple subsequent short periods between long periods. There are no time gaps in the data-- the start of one period is always the same as the end of the previous one.</p> <p>What's a good set-based way (no cursors!) to perform this merging?</p> <p>Existing data (simplified) looks like this:</p> <pre><code>UnitsSold Start End --------------------------------------------------- 10 06-12-2013 08:03 06-12-2013 12:07 12 06-12-2013 12:07 06-12-2013 16:05 1 06-12-2013 16:05 06-12-2013 16:09 1 06-12-2013 16:09 06-12-2013 16:13 7 06-12-2013 16:13 06-12-2013 20:10 </code></pre> <p>Desired output would look like this:</p> <pre><code>UnitsSold Start End --------------------------------------------------- 10 06-12-2013 08:03 06-12-2013 12:07 14 06-12-2013 12:07 06-12-2013 16:13 7 06-12-2013 16:13 06-12-2013 20:10 </code></pre> <p>Unfortunately we're still on SQL Server 2008 R2, so we can't leverage the cool new window functions in SQL Server 2012, which might make this problem easier to solve efficiently. </p> <p>There's a good discussion of a similar problem in <a href="https://stackoverflow.com/questions/15161262/merge-adjacent-rows-in-sql">Merge adjacent rows in SQL?</a>. I particularly like the PIVOT/UNPIVOT solution, but I'm stumped for how to adapt it to my problem. </p>
    singulars
    1. This table or related slice is empty.
    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.
    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