在1和最大数量CTE之间插入缺失的数字

时间:2014-09-23 08:11:27

标签: sql-server tsql

列MissingNumber是最大数字,myID是Identity列。 IF 1是所有这些数据的最小数量是否有一个SQL查询,我可以使用它来复制从1到由myID分区的最大数字的顺序。

DECLARE @NumbersTable TABLE
(
myID int NOT NULL,
OtherColumn Varchar(20) NOT NULL,
MissingNumber INT NOT NULL
)

INSERT INTO @NumbersTable VALUES
(1,'Apple', 10)
INSERT INTO @NumbersTable VALUES
(2,'Orange', 5)
INSERT INTO @NumbersTable VALUES
(3,'Kiwi', 15)
INSERT INTO @NumbersTable VALUES
(4,'Mango', 4)
INSERT INTO @NumbersTable VALUES
(5,'Strawberry', 8)

SELECT * FROM @NumbersTable

结果

myID        OtherColumn          MissingNumber
----------- -------------------- -------------
1           Apple                10
2           Orange               5
3           Kiwi                 15
4           Mango                4
5           Strawberry           8

(5 row(s) affected)

myID 1和2(苹果和橘子)的输出

myID        OtherColumn          MissingNumber
----------- -------------------- -------------
1           Apple                1
1           Apple                2
1           Apple                3
1           Apple                4
1           Apple                5
1           Apple                6
1           Apple                7
1           Apple                8
1           Apple                9
1           Apple                10
2           Orange               1
2           Orange               2
2           Orange               3
2           Orange               4
2           Orange               5

3 个答案:

答案 0 :(得分:1)

数字表!

谷歌周围的数字表,自己动手,或使用one I made earlier

SELECT NumbersTable.my.ID
     , NumbersTable.OtherColumn
     , numbers.number As MissingNumber
FROM   @NumbersTable As NumbersTable
 INNER
  JOIN dbo.numbers
    ON numbers.number BETWEEN 1 AND NumbersTable.MissingNumber
WHERE  NumbersTable.myID IN (1, 2)

答案 1 :(得分:1)

最简单的方法是使用数字表。如果您还没有,则可以使用master..spt_values生成一系列数字:

INSERT @NumbersTable (myID, OtherColumn, MissingNumber)
SELECT myID, othercolumn, m.number FROM @NumbersTable n
OUTER APPLY (
    SELECT number FROM master..spt_values 
    WHERE TYPE = 'P' AND number BETWEEN 1 AND n.MissingNumber - 1    
    ) m

INSERT @NumbersTable (myID, OtherColumn, MissingNumber)
SELECT myID, OtherColumn, m.number FROM @NumbersTable n
INNER JOIN master..spt_values m ON m.number < n.MissingNumber
WHERE TYPE = 'P' AND m.number > 0

Sample SQL Fiddle

答案 2 :(得分:0)

找到一篇有趣的文章,得到了我需要的答案,而不是每个人

https://www.simple-talk.com/sql/t-sql-programming/find-missing-date-ranges-in-sql/

;WITH cteMyNumber
AS
(
SELECT myID,OtherColumn,MissingNumber
FROM @NumbersTable
UNION ALL 
SELECT myID,OtherColumn,MissingNumber -1
FROM cteMyNumber
WHERE MissingNumber >0
)
SELECT * FROM cteMyNumber
WHERE MissingNumber<>0
ORDER BY myID,MissingNumber