Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

query che duplicherà i record in base alla quantità

Dati di prova

CREATE TABLE Test_Table
(
   PartNumber       VARCHAR(20) , 
   Quantity         INT, 
   [Description]    VARCHAR(20), 
   Category         VARCHAR(20),  
   Size             VARCHAR(20), 
   Tags             VARCHAR(20)
)
GO
INSERT INTO Test_Table 
VALUES
('Part 100', 3, 'Description 100', 'Cat100', 'Size100', 'Tag100'),
('Part 101', 2,'Description 101', 'Cat101', 'Size101', 'Tag101')
GO

Interroga

;WITH CTE (Vals) 
AS (
    SELECT 1 

     UNION ALL

    SELECT 1 + Vals 
    FROM CTE WHERE Vals < 99
   )
SELECT A.PartNumber
      , 1 AS QTY
      ,A.Category
      ,A.[Description]
      ,A.Size
      ,A.Tags
FROM       Test_Table A 
INNER JOIN CTE C   ON C.Vals <= A.Quantity
ORDER BY A.PartNumber

Set di risultati

╔════════════╦═════╦══════════╦═════════════════╦═════════╦════════╗
║ PartNumber ║ QTY ║ Category ║   Description   ║  Size   ║  Tags  ║
╠════════════╬═════╬══════════╬═════════════════╬═════════╬════════╣
║ Part 100   ║   1 ║ Cat100   ║ Description 100 ║ Size100 ║ Tag100 ║
║ Part 100   ║   1 ║ Cat100   ║ Description 100 ║ Size100 ║ Tag100 ║
║ Part 100   ║   1 ║ Cat100   ║ Description 100 ║ Size100 ║ Tag100 ║
║ Part 101   ║   1 ║ Cat101   ║ Description 101 ║ Size101 ║ Tag101 ║
║ Part 101   ║   1 ║ Cat101   ║ Description 101 ║ Size101 ║ Tag101 ║
╚════════════╩═════╩══════════╩═════════════════╩═════════╩════════╝