如何填补表中行的间隙

时间:2015-12-12 13:32:56

标签: sql sql-server tsql

我有mart表,我的行有空白。我尝试使用循环条件,但我无法继续

CREATE TABLE Mart
    (martID int, mart int)
;

INSERT INTO Mart
    (martID, mart)
VALUES
    (1, 10),
    (4, 12),
    (6, 20)
;

OutPut

martID       mart
1             10
2             0
3             0
4             12
5             0
6             20

到目前为止我的代码

select  max(martId) as nr
        from    Mart
        union all
        select  nr - 1
        from    numbers
        where   nr > 1

4 个答案:

答案 0 :(得分:1)

希望您Number表包含一系列无间隙的数字。试试这个

SELECT nr, 
       COALESCE(mart, 0) AS mart 
FROM   numbers n 
       LEFT OUTER JOIN mart m 
                    ON m.martid = n.nr 
WHERE  n.nr BETWEEN (SELECT Min(martid) 
                     FROM   mart) AND (SELECT Max(martid) 
                                       FROM   mart) 

如果您没有numbers表格,请参考此link以生成SQL Server中的值序列。我更喜欢STACKED CTE方法

;WITH e1(n) AS
(
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), -- 10
e2(n) AS (SELECT 1 FROM e1 CROSS JOIN e1 AS b), -- 10*10
e3(n) AS (SELECT 1 FROM e1 CROSS JOIN e2) -- 10*100
  SELECT n = ROW_NUMBER() OVER (ORDER BY n) FROM e3 ORDER BY n;

答案 1 :(得分:1)

如果您只想显示数据,可以使用以下代码:

SELECT 
    n.MartId, 
    ISNULL(m.mart, 0)
FROM 
    numbers n
    LEFT JOIN Mart m ON n.MartId = m.martID
ORDER BY
    n.MartId

答案 2 :(得分:0)

可能是这个作品

declare @Mart TABLE 
    (martID int, mart int)
;

INSERT INTO @Mart
    (martID, mart)
VALUES
    (1, 10),
    (4, 12),
    (6, 20)
;
declare @MinNo int
declare @MaxNo int
declare @IncrementStep int
set @MinNo = 1
set @MaxNo = 10
set @IncrementStep = 1

;with C as
(
  select @MinNo as Num
  union all 
  select Num + @IncrementStep
  from C 
  where Num < @MaxNo
)      
select Num,
CASE WHEN mart IS NOT NULL THEN mart ELSE 0 END AS NUMBER
from C  
LEFT JOIN @Mart t
ON t.martID = c.Num

答案 3 :(得分:0)

尝试使用递归cte,

DECLARE @Max_var INT=(SELECT Max(martid)
  FROM   Mart);

WITH cte
     AS (SELECT 1 AS Value
         UNION ALL
         SELECT Value=Value + 1
         FROM   cte
         WHERE  ( Value + 1 ) <= @Max_var)
SELECT Value,
       Isnull(mart, 0)
FROM   cte A
       LEFT JOIN Mart B
              ON A.Value = B.martID