Вы можете использовать КУРСОР, чтобы получить желаемый результат-
DECLARE @id_order INT
DECLARE @id_Status_order INT
DECLARE @dsc_statue VARCHAR(100)
DECLARE @lead INT
DECLARE @LoopCount INT
DECLARE @TmpTable TABLE
(
id_order INT, dsc_status VARCHAR(200), lead INT, iter INT
)
DECLARE @id_order_prev INT
DECLARE @dsc_statue_prev VARCHAR(100)
DECLARE @lead_prev INT
DECLARE db_cursor CURSOR FOR
SELECT id_order,Status_Order,dsc_status,lead
FROM
(
SELECT id_order,dsc_status,lead,
CASE
WHEN dsc_status = 'placed' THEN 1
WHEN dsc_status = 'confirmed' THEN 2
WHEN dsc_status = 'shipped' THEN 3
END Status_Order
FROM your_table
)A
ORDER BY 1,2
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @id_order,@id_Status_order ,@dsc_statue,@lead
WHILE @@FETCH_STATUS = 0
BEGIN
IF @id_order_prev IS NULL
BEGIN
SET @id_order_prev = @id_order
SET @dsc_statue_prev = @dsc_statue
SET @lead_prev = @lead
END
ELSE
BEGIN
SET @LoopCount = 0
WHILE @LoopCount <= CASE WHEN @id_order_prev = @id_order THEN ABS(@lead_prev-@lead) ELSE @lead_prev END
BEGIN
INSERT INTO @TmpTable (id_order,dsc_status,lead,iter)
VALUES (@id_order_prev,@dsc_statue_prev,@lead_prev,@LoopCount)
SET @LoopCount = @LoopCount + 1
END
SET @id_order_prev = @id_order
SET @dsc_statue_prev = @dsc_statue
SET @lead_prev = @lead
END
FETCH NEXT FROM db_cursor INTO @id_order,@id_Status_order ,@dsc_statue,@lead
IF @@FETCH_STATUS <> 0
BEGIN
SET @LoopCount = 0
WHILE @LoopCount <= @lead
BEGIN
INSERT INTO @TmpTable (id_order,dsc_status,lead,iter)
VALUES (@id_order_prev,@dsc_statue_prev,@lead_prev,@LoopCount)
SET @LoopCount = @LoopCount + 1
END
END
END
CLOSE db_cursor
DEALLOCATE db_cursor
SELECT *
FROM @TmpTable
ORDER BY 1