nr, thanks again for pointing me in the right direction. I finally understand better now about the logic that went into your code. It looks to me that it's the same that is described in my book as 'Correlated Subquerries'. It still has not fully sunk in, but enough to go to the next step. In the original post I left out a another dimension to the question. In the same [Part] table, there are 6 different categories of parts all with seperate PartSuffix numbers ranging from 0000 to XXXX. I came up with this code based on yours and it actually works when there's multiple category data in the table!:select min(PartSuffix) as PartSuffix, count(*) as 'Parts Available'from( select PartSuffix, cnt = ( select count(*) from Part a2 join (select PartCategoryID, PartCategoryCode from PartCategory) p2 on a2.PartCategoryID = p2.PartCategoryID where a2.PartSuffix <= a1.PartSuffix and PartStatus = 0 and p2.PartCategoryCode = 2 ) from Part a1 join (select PartCategoryID, PartCategoryCode from PartCategory) p1 on a1.PartCategoryID = p1.PartCategoryID where a1.PartStatus = 2 and p1.PartCategoryCode = 2) agroup by cnt
Here's my test table:Category Name Part Number PartStatusTooling 0320-0000 2Tooling 0320-0001 2Tooling 0320-0002 0Tooling 0320-0003 0Tooling 0320-0004 0Tooling 0320-0005 0Tooling 0320-0006 2Tooling 0320-0007 2Tooling 0320-0008 2Tooling 0320-0009 2Tooling 0320-0010 2Tooling 0320-0011 2Tooling 0320-0012 2Tooling 0320-0013 2Tooling 0320-0014 0Tooling 0320-0015 0Tooling 0320-0016 0Tooling 0320-0017 0Tooling 0320-0018 0Tooling 0320-0019 2Tooling 0320-0020 2A/W 0360-0000 0A/W 0360-0001 0A/W 0360-0002 0A/W 0360-0003 2A/W 0360-0004 2A/W 0360-0005 0A/W 0360-0006 0A/W 0360-0007 0A/W 0360-0008 2A/W 0360-0009 2A/W 0360-0010 2A/W 0360-0011 2A/W 0360-0012 2A/W 0360-0013 2
And here's the result when PartCategoryCode = 2 (Tooling)PartSuffix Parts Available0000 20006 80019 2
And when PartCategoryCode = 5 (A/W)PartSuffix Parts Available0003 20008 6
Sweet! You can see the results check out with the table. Basically I joined two sub-selected tables one on the inside (the a2 side) of the <= and the other on the outside (the a1 side) to filter on the PartCategoryCode. Now I'm curious since the sub-selected table code: (select PartCategoryID, PartCategoryCode from PartCategory)
is the same on either side, is there a better way to do it?Thanks,- jimanny