奇怪的SQL条件日期,STUCK

时间:2013-01-24 20:02:05

标签: sql sql-server sql-server-2008 tsql sql-server-2005

我在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

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

谢谢!!!!

谢谢!!!

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

即。

  1. 对于每个月,找到小于等于本月的月份,但是 使用非null DateTime;
  2. 将DateTime值查找到上一步中找到的月份

答案 2 :(得分: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 demo

编辑将交叉申请更改为外部申请,@ Lamak说得对。