插入行以填充序列

时间:2016-10-10 15:57:16

标签: sql

我试图在Year列中插入缺少年份的行。我们的想法是在2016年之前每年都有一个年份和价值,从给定身份证的第一年开始。这是我目前的状态:

id  year    value
a   2016    100
a   2015    90
a   2007    60
b   2016    120
b   2014    105
c   2015    110
c   2014    90
d   2016    150

这是我想要的状态:

id  year    value
a   2016    100
a   2015    90
a   2014    60
a   2013    60
a   2012    60
a   2011    60
a   2010    60
a   2009    60
a   2008    60
a   2007    60
b   2016    120
b   2015    105
b   2014    105
c   2016    110
c   2015    110
c   2014    90
d   2016    150

因此,用前一年的价值填补缺失的年份。如何在Excel,SQL或VBA中实现这一目标?我可以把它扔进一个访问数据库来完成工作。我现在唯一能想到的就是将我当前的表连接到SQL中的表中,并且我需要多年来重新填充NULL值。非常感谢任何帮助。谢谢!

编辑:如何使用SQL专门执行此操作?

1 个答案:

答案 0 :(得分:0)

这可以通过VBA,蛮力方法完成,如下所示。 如果您有任何问题,请与我们联系。

Dim ws As Worksheet
' assuming data is always sorted by id
Dim Row As Integer
Dim curID, prevID As String
Dim curYr, prevYr As Integer
Dim prevVal As Integer

Set ws = ThisWorkbook.ActiveSheet

Row = ws.Cells.SpecialCells(xlCellTypeLastCell).Row
' This does 2 things gets the prevID and makes sure previous line selects the actual last row
prevID = ""
Do
   prevID = ws.Cells(Row, 1)
   prevYr = ws.Cells(Row, 2)
   prevVal = ws.Cells(Row, 3)
   Row = Row - 1
Loop Until prevID <> "" Or Row = 2

While Row > 2
   curID = ws.Cells(Row, 1)
   curYr = ws.Cells(Row, 2)

   ' next id
   If curID <> prevID Then
      Row = Row + 1
      For i = 2016 To (prevYr + 1) Step -1
         ws.Rows(Row).Insert shift:=xlShiftDown
         ws.Cells(Row, 1) = prevID
         ws.Cells(Row, 2) = i
         ws.Cells(Row, 3) = prevVal
      Next i
      Row = Row - 1
      prevID = curID
      prevYr = curYr
      prevVal = ws.Cells(Row, 3)
   ' next year
   ElseIf curYr - 1 = prevYr Then
      prevID = curID
      prevYr = curYr
      prevVal = ws.Cells(Row, 3)
   ' in between
   Else
      Row = Row + 1
      For i = (prevYr + 1) To (curYr - 1)
         ws.Rows(Row).Insert shift:=xlShiftDown
         ws.Cells(Row, 1) = prevID
         ws.Cells(Row, 2) = i
         ws.Cells(Row, 3) = prevVal
      Next i
      If prevYr = curYr Then
         Row = Row - 1
      End If
      prevYr = curYr
   End If

   Row = Row - 1
Wend