0
votes

I have a database table that Stores Maximum and Minimum Price Breaks for a Product. enter image description here

Does anyone know of the SQL which say if I have a break from one Max to the Min of the next item. E.g. 1-10 12-20 I would like it to return me either the numbers that are missing or at the very least a count or bool if it can detect a break from the Absolute Min and the Absolute Max by going through each range.

SQL Server (MSSQL) 2008

2
Anything you have tried till now, share please? - Anshu
Which RDBMS? They all have different capabilities, syntax, optimisations, etc. And are your values inclusive and/or exclusive? (For example, do you have a gap between 10 and 11 in your example? Or is there an overlap because 2 rows have the value 20?) And do you already know that there are no overlaps, or shoudl we account for that possiblity as well? - MatBailie
MSSQL 2008 I would not like to account for overlaps as that will be down to user error but if someone can help on that it would be good but its mainly finding a gap in a Max and Min Squence - TheMonkeyMan
MSSQL 2012 Supports LEAD/LAG analytic functions (window functions). See my comment below. If this isn't available for 2008, a join can be used instead. - Jon Armstrong - Xgc

2 Answers

3
votes

For a database that supports window functions, like Oracle:

SELECT t.*
     , CASE LAG(maxq+1, 1, minq) OVER (PARTITION BY prod ORDER BY minq)
          WHEN minq
          THEN 0
          ELSE 1
       END AS is_gap
  FROM tbl t
;

This will produce is_gap = 1 for a row that forms a gap with the previous row (ordered by minq). If your quantity ranges can overlap, the required logic would need to be provided.

http://sqlfiddle.com/#!4/f609e/4

1
votes

Something like this, giving max quantities that aren't the overall max for the product and don't have a min quantity following them:

select prev.tbProduct_Id,prev.MaxQuantity
  from yourtable prev
  left join (select tbProduct_ID, max(MaxQuantity) MaxQuantity from yourtable group by tbProduct_id) maxes
    on maxes.tbProduct_ID=prev.tbProduct_Id and maxes.MaxQuantity=prev.MaxQuantity
  left join yourtable next
    on next.tbProduct_Id=prev.tbProduct_Id and next.MinQuantity=prev.MaxQuantity+1
  where maxes.tbProduct_Id is null and next.tbProduct_Id is null;

This would fail on your sample data, though, because it would expect a row with MinQuantity 21, not 20.