Теперь я понимаю, что вы хотите, и я думаю, вам понадобится курсор. Одно важное замечание: вы должны указать order by
, когда используете TOP
, если вам все равно , какие строки возвращаются. Прочтите эту статью.
Вот как вы бы это реализовали:
--create some sample data that you gave
declare @inventory table ( PartNumber int,
Quantity int,
NewCount int,
diff int)
insert into @inventory
values
(2871451,1,0,1),
(4932615,6,1,5)
declare @PARTSREMAININGFIFO table ( id int,
PartNumber int,
PartDescription varchar(64),
Quantity int,
TotalPrice decimal (8,6),
brand varchar(64),
Location varchar(16),
Account varchar(64))
insert into @PARTSREMAININGFIFO
values
(9183,2871451,'AFM DEVICE GASKET',1,19.815225,'CUMMINS','A1','6015-Z'),
(9183,2871451,'AFM DEVICE GASKET',1,19.815225,'CUMMINS','A2','6015-Z'), --notice the extra (2nd) row here for part 2871451
(9183,2871451,'AFM DEVICE GASKET',1,19.815225,'CUMMINS','A3','6015-Z'), --notice the extra (3nd) row here for part 2871451
(3264,4932615,'GASKET',1,2.907144,'CUMMINS','A1','6015-Z'),
(9780,4932615,'GASKET',1,5.053475,'CUMMINS','A1','6015-Z'),
(9781,4932615,'GASKET',1,5.053475,'CUMMINS','A1','6015-Z'),
(9782,4932615,'GASKET',1,5.053475,'CUMMINS','A1','6015-Z'),
(9783,4932615,'GASKET',1,5.053475,'CUMMINS','A1','6015-Z'),
(9783,4932615,'GASKET',1,5.053475,'CUMMINS','A6','6015-Z') --notice the 6th (extra) row here for part 4932615
--staging table for your results
declare @tempResults table ( id int,
PartNumber int,
PartDescription varchar(64),
Quantity int,
TotalPrice decimal (8,6),
brand varchar(64),
Location varchar(16),
Account varchar(64))
declare cur cursor local fast_forward for
select distinct
PartNumber,
diff
from (select
PartNumber,
Quantity,
NewCount,
diff
from @inventory
where NewCount <> Quantity) x
declare @partNumber int
declare @diff int
open cur
fetch next from cur into @partNumber, @diff
while @@FETCH_STATUS = 0
begin
insert into @tempResults
select top (@diff)
id,
PartNumber,
PartDescription,
Quantity,
TotalPrice,
Brand,
Location,
Account
from @PARTSREMAININGFIFO
where PartNumber = @partNumber
order by Quantity --note you need to specify WHAT you want to order by
fetch next from cur into @partNumber, @diff
end
select *
from @tempResults
order by PartNumber
close cur
deallocate cur