Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL Calculate (time) gap between occurrences in a log
    primarykey
    data
    text
    <p>I have tables that record when certain items were sent or returned to a particular location, and I want to work out the intervals between each time a particular item is returned.</p> <p>Sample data:</p> <pre><code>Item ReturnDate: Item1, 20120101 Item1, 20120201 Item1, 20120301 Item2, 20120401 Item2, 20120601 </code></pre> <p>So in this case, we can see that the there was a month gap until Item 1 was returned the first time, and another month before it was returned the second time. Item 2 came back after 2 months.</p> <p>My starting point is:</p> <pre><code>Select r1.Item, r1.ReturnDate, r2.Item, r2.ReturnDate, DateDiff(m, r1.ReturnDate, r2.ReturnDate) from Returns r1 inner join Returns r2 on r2.VehicleNo = r1.VehicleNo </code></pre> <p>However, in the this sample, each item is compared to every other instance where it has been returned - and not just the next one. So I need to limit this query so it will only compare adjacent returns.</p> <p>One solution is to tag each return with an count (of the number of times that item has been returned):</p> <pre><code>Item ReturnDate, ReturnNo: Item1, 20120101, 1 Item1, 20120201, 2 Item1, 20120301, 3 Item2, 20120401, 1 Item2, 20120601, 2 </code></pre> <p>This would enable me to use the following T-SQL (or similar):</p> <pre><code>Select r1.Item, r1.ReturnDate, r2.Item, r2.ReturnDate, DateDiff(m, r1.ReturnDate, r2.ReturnDate) from Returns r1 inner join Returns r2 on r2.VehicleNo = r1.VehicleNo and (r1.ReturnNo + 1 = r2.ReturnNo) </code></pre> <p>My first question is whether the is a sensible/optimal approach or whether there is a better approach?</p> <p>Secondly, what is the easiest/slickest means of calculating the ReturnNo?</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.
    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