根据列值添加列

时间:2015-03-17 14:12:24

标签: sql sql-server sql-server-2008 sql-server-2012

我有这张桌子:

PersonID    DateKey   C/L
   1       20140903    8 
   1       20140904    null
   1       20140906    10 
   1       20140908    null  
   2       20140903    18 
   2       20140904    null
   2       20140906    30 
   2       20140908    null

我需要添加另一列并重复[C/L]的值,结果表应如下所示:

PersonID    DateKey   C/L      C/L_New
   1       20140903    8          8
   1       20140904    null       8
   1       20140906    10         10
   1       20140908    null       10
   2       20140903    18         18
   2       20140904    null       18
   2       20140906    30         30
   2       20140908    null       30

2 个答案:

答案 0 :(得分:2)

我想你想要这个(假设DateKey是日期或日期时间列):

SELECT PersonID,    
       DateKey,
       [C/L],
       [C/L_New] = ISNULL([C/L], (SELECT TOP 1 t2.[C/L]
                                  FROM dbo.TableName t2
                                  WHERE t2.PersonID = t.PersonID
                                  AND   t2.DateKey <= t.DateKey
                                  AND   t2.[C/L] IS NOT NULL
                                  ORDER BY DateKey DESC))
FROM dbo.TableName t
Order By PersonID, DateKey

修改:DEMO

答案 1 :(得分:1)

如果当前行的值为NULL,我猜你想要前一行的值。

SQL Server 2012 ,您可以使用LAG功能:

SELECT PersonID
      ,DateKey
      ,[C/L]
      ,COALESCE([C/L], LAG([C/L], 1, NULL) OVER (ORDER BY PersonID, DateKey)) AS [C/L_New]
FROM YourTable