SQL-在缺少值的行中插入带有前一行信息的行

时间:2019-08-05 20:03:32

标签: sql sql-server

我已查询SQL Server数据库中的表,这些表返回带有数量的// Updating the likee if (ctx._source.swipedOnBy != null) { if (!ctx._source.swipedOnBy.contains(params.swipedOnBy)) { ctx._source.swipedOnBy.add(params.swipedOnBy) } } else { ctx._source.swipedOnBy = new int[ ] {params.swipedOnBy} } // Updating the liker if (ctx._source.liked != null) { if (ctx._source.liked.contains(params.liked)) { ctx._source.liked.add(params.liked) } } else { ctx._source.liked = new int[] {params.liked} } CId的范围从0到6)。

结果:

CId

我想将缺少的aNbr kNbr CId Qty ---- ---- --- --- 6814 77 0 10 6814 77 2 30 6814 77 3 48 6814 77 4 60 6855 32 2 20 6855 32 6 30 1768 10 0 0 1768 47 0 0 插入到具有前一行CId-> qty的结果表中,如果组中没有以前的值,则将qty插入为0

预期结果:我在行的前面添加了CId字符以指示实际值与预期值之间的差异。

|

我认为加入同一个表格应该可以,但是不确定如何执行此操作,或者在Google上未获得任何相关信息。

有人可以告诉我我的方法正确还是可行? (将表与其自身连接并查看上一行的值)

应用更改后的更新结果:

    aNbr  kNbr  CId  Qty
    ----  ----  ---  ---
    6814   77    0   10
   |6814   77    1   10
    6814   77    2   30
    6814   77    3   48
    6814   77    4   60
   |6814   77    5   60
   |6814   77    6   60
   |6855   32    0   0
   |6855   32    1   0
    6855   32    2   20
   |6855   32    3   20
   |6855   32    4   20
   |6855   32    5   20
    6855   32    6   30
    1768   10    0   0
   |1768   10    1   0
   |1768   10    2   0
   |1768   10    3   0
   |1768   10    4   0
   |1768   10    5   0
   |1768   10    6   0
    1768   47    0   0
   |1768   47    1   0
   |1768   47    2   0
   |1768   47    3   0
   |1768   47    4   0
   |1768   47    5   0
   |1768   47    6   0

1 个答案:

答案 0 :(得分:1)

使用cross join生成行,使用left join引入当前值:

select ak.aNbr, ak.kNbr, c.cid, coalesce(t.qty, 0) as qty
from (select distinct aNbr, kNbr from t) ak cross join
     (values (0), (1), (2), (3), (4), (5), (6)
     ) v(cid) left join
     t
     on t.aNbr = ak.aNbr and t.kNbr = ak.kNbr and t.cid = v.cid
order by aNbr, kNbr, CId;

编辑:

我知道,您想先重复最近的数量。 lag(ignore nulls)的好地方。 SQL,SQL Server不支持该功能。相反,我们可以使用outer apply

select ak.aNbr, ak.kNbr, c.cid, coalesce(t.qty, 0) as qty
from (select distinct aNbr, kNbr from t) ak cross join
     (values (0), (1), (2), (3), (4), (5), (6)
     ) v(cid) outer apply
     (select top (1) t.*
      from t
      where t.aNbr = ak.aNbr and t.kNbr = ak.kNbr and t.cid <= v.cid
      order by t.cid desc
     ) t
order by aNbr, kNbr, CId;

如果您知道数量总是在增加,则可以:

select ak.aNbr, ak.kNbr, c.cid,
       max(coalesce(t.qty, 0)) over (partition by ak.aNbr, ak.kNbr order by c.cid) as qty
from (select distinct aNbr, kNbr from t) ak cross join
     (values (0), (1), (2), (3), (4), (5), (6)
     ) v(cid) left join
     t
     on t.aNbr = ak.aNbr and t.kNbr = ak.kNbr and t.cid = v.cid
order by aNbr, kNbr, CId;

这应该比outer apply有更好的性能。