Skip to content Skip to sidebar Skip to footer

How Can I Create Duplicate Records Based The Value In Another Table

I have two tables in my database, Work_Order table which is the source table where work order information's stored i also have Work_Schedule table which contains work schedules wh

Solution 1:

This seems like a natural for a recursive CTE:

with cte as (select convert(datetime, '2019-07-22 7:00AM') as dt, workorder, 1 as workcenter, qtyperh as target,
             itemcode, size, (qty - qtyperh) as qty, qtyperh
      from t
      union all
      selectdateadd(hour, 1, dt), workorder, workcenter,
             (casewhen qty > qtyperh then qtyperh else qty end) as target,
             itemcode, size, (qty - qtyperh), qtyperh
      from cte
      where qty > 0
     )
select cte.*,
       dateadd(second, 60 * 60 * target / qtyperh, dt) as end_dt
from cte
order by workorder, dt;

Here is a db<>fiddle.

Solution 2:

Is that what are you after?

CREATETABLE T(
  WorkOrder INT,
  ItemCode INT,
  Size VARCHAR(25),
  Qty INT,
  QtyPerH INT
);

INSERTINTO T VALUES
(41051,        600111,    '14L-16.1',        55,          10),
(41052,        600112,    '14L-16.2',        55,          5);

SELECT T.*FROM T CROSS APPLY
(
  SELECT1 N
  FROM master..spt_values
  WHERE [Type] ='P'AND
        [Number] < (T.Qty / T.QtyPerH)
) TT;

Returns:

+-----------+----------+----------+-----+---------+
| WorkOrder | ItemCode |   Size   | Qty | QtyPerH |
+-----------+----------+----------+-----+---------+
|     41051 |   600111 | 14L-16.1 |  55 |      10 |
|     41051 |   600111 | 14L-16.1 |  55 |      10 |
|     41051 |   600111 | 14L-16.1 |  55 |      10 |
|     41051 |   600111 | 14L-16.1 |  55 |      10 |
|     41051 |   600111 | 14L-16.1 |  55 |      10 |
|     41052 |   600112 | 14L-16.2 |  55 |       5 |
|     41052 |   600112 | 14L-16.2 |  55 |       5 |
|     41052 |   600112 | 14L-16.2 |  55 |       5 |
|     41052 |   600112 | 14L-16.2 |  55 |       5 |
|     41052 |   600112 | 14L-16.2 |  55 |       5 |
|     41052 |   600112 | 14L-16.2 |  55 |       5 |
|     41052 |   600112 | 14L-16.2 |  55 |       5 |
|     41052 |   600112 | 14L-16.2 |  55 |       5 |
|     41052 |   600112 | 14L-16.2 |  55 |       5 |
|     41052 |   600112 | 14L-16.2 |  55 |       5 |
|     41052 |   600112 | 14L-16.2 |  55 |       5 |
+-----------+----------+----------+-----+---------+

Demo

Post a Comment for "How Can I Create Duplicate Records Based The Value In Another Table"