1

我和在 SQL Server 中创建视图

以下是我的结果,基于此,我必须实际实现下面第二个表中显示的结果

PersonID      MonthYear     DateTimevalue
----------    ----------    --------------
 1             201101        NULL
 1             201102        NULL
 1             201103        2011-03-10 09:35:57.387
 1             201104        2011-04-26 13:25:00.050
 1             201105        NULL
 1             201106        NULL
 1             201107        2011-07-30 16:49:26.050
 1             201108        NULL
 1             201109        2011-09-21 13:33:42.273
 1             201110        2011-10-20 08:55:59.873
 1             201111        NULL
 1             201112        NULL

所以,当 DateTimeValue 为 NULL 的情况下,我们需要取上个月的值

如下表所示

PersonID      MonthYear     DateTimevalue
----------    ----------    --------------
 1             201101        NULL
 1             201102        NULL
 1             201103        2011-03-10 09:35:57.387
 1             201104        2011-04-26 13:25:00.050
 1             201105        2011-04-26 13:25:00.050
 1             201106        2011-04-26 13:25:00.050
 1             201107        2011-07-30 16:49:26.050
 1             201108        2011-07-30 16:49:26.050
 1             201109        2011-09-21 13:33:42.273
 1             201110        2011-10-20 08:55:59.873
 1             201111        2011-10-20 08:55:59.873
 1             201112        2011-10-20 08:55:59.873

任何帮助都会很棒!!!!

谢谢 !!!!

谢谢 !!!

4

3 回答 3

2

尝试以下操作:

SELECT  A.PersonID, 
        A.MonthYear, 
        ISNULL(A.DateTimeValue,B.DateTimeValue) DateTimeValue
FROM YourTable A
OUTER APPLY (   SELECT TOP 1 DateTimeValue 
                FROM YourTable
                WHERE PersonID = A.PersonID 
                AND MonthYear < A.MonthYear 
                AND DateTimeValue IS NOT NULL
                ORDER BY MonthYear DESC) B
于 2013-01-24T20:21:14.277 回答
0

Sql Server 是否允许在 Select 子句中嵌套 SQL?如果是这样:

select personId, monthYear, 
       (select T2.DateTimeValue from Tbl T2 
        where T2.monthYear=(select max(T3.monthYear) from Tbl T3
                            where T3.personid=T1.personId and T3.monthYear<=T1.monthYear
                              and T3.DateTimeValue is not null
                           )
       )
from Tbl T1

IE

  1. 对于每个月,找到小于等于该月的月份,但 DateTime 不为空;
  2. 将 DateTime 值查找到上述步骤中找到的月份
于 2013-01-24T20:10:51.670 回答
0

试试这个:

select t1.personid
  , t1.monthyear
  , datetimevalue = prev.datetimevalue
from t1
  outer apply
  (
    select top 1 datetimevalue
      , personid
      , monthyear
    from t1 prev
    where prev.monthyear <= t1.monthyear
      and prev.datetimevalue is not null
    order by monthyear desc
) prev
order by t1.personid
  , t1.monthyear

SQLFiddle 演示

编辑为将cross apply更改为external apply,@Lamak 是对的。

于 2013-01-24T20:20:15.683 回答