質問

I have a table tracking stock changes with the following fields:

InvNo int
InStock int
AdjustedOn datetime

I'm trying to write a query that will return distinct InvNo values where the most recent InStock Value is at least 10 greater/less than the last InStock value for the given InvNo.

I'm also trying to write a similar query to do the same thing, but for InvNo's where any InStock value is 10 greater/less than the previous value.

I've done this before and I know it's not that complicated, but just having a little trouble remembering how to do it in a sensible amount of time this morning.

EDIT: There's no Id field in the table, but I could add one if it would make the query easier.

役に立ちましたか?

解決

you must do a self join to include in sql query both the most recent row as well as the current row...

Select c.InvNo, c.inStock current, r.InStock Previous
From table c join table r 
    on r.invNo = c.invNo
       And r.AdjustedOn =
         (Select Max(AdjustedOn)
          From table 
          Where invNo = c.InvNo
            And adjustedOn < c.AdjustedOn)
Where c.InStock >= r.Instock + 10 Or
      c.Instock <= r.Instock - 10

This gives you all rows where the change at that point in time, was 10 or more from the previous change, but it includes changes that occurred in the past, before the most recent change. If you want the query to only include the rows representing the most recent change, then add another predicate sub query to the outer sql...

Select c.InvNo, c.inStock current, r.InStock Previous
From table c join table r 
    on r.invNo = c.invNo
       And r.AdjustedOn =
         (Select Max(AdjustedOn)
          From table 
          Where invNo = c.InvNo
            And adjustedOn < c.AdjustedOn)
Where (c.InStock >= r.Instock + 10 Or
       c.Instock <= r.Instock - 10)
  And c.AdjustedOn =
    (Select Max(AdjustedOn)
     From table 
     Where invNo = c.InvNo)

他のヒント

What version of SQL?

  • 2012, look at the LAG and LEAD functions
  • 2008, look at the ROW_NUMBER function
  • 2005 or earlier, self-joins are your only option
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top