SQL最近的过去日期

时间:2015-04-06 21:55:02

标签: sql sql-server date

我在处理SQL上的一些数据时遇到问题,并按最近的日期返回一些值。我有两张桌子:

表1

    ID       Content         Date
--------------------------------------------
   123    X              2013-11-18 
   123    ZE             2013-11-29  
   233    YX             2013-12-30
   233    XX             2013-12-28  
   444    Z              2014-02-24

表2

 ID       Value         Validation Date
--------------------------------------------
   123    0.54              2013-11-11
   123    0.42              2013-11-18 
   123    0.32              2013-11-27 
   233    1.2               2013-12-4 
   233    1.1               2013-12-28 
   233    1.0               2013-12-29 
   444    4                 2014-02-11
   444    3                 2014-02-15
   444    2                 2014-02-23

我假装的输出类似于:

    ID       Content         Date          Value      Validation Date
------------------------------------------------------------------------
   123    X              2013-11-18       0.42         2013-11-18
   123    ZE             2013-11-29       0.32         2013-11-27
   233    YX             2013-12-30       1.0          2013-12-29
   233    XX             2013-12-28       1.1          2013-12-28
   444    Z              2014-02-24       2            2014-02-23

所以我想返回验证日期最接近日期的值(验证日期必须始终小于日期)。你能帮我么?表1和表2中的ID不是唯一的。

4 个答案:

答案 0 :(得分:1)

您可以使用以下查询:

SELECT ID, Content, [Date], Value, [Validation Date]
FROM (
   SELECT t1.ID, Content, [Date], Value, [Validation Date], 
          ROW_NUMBER() OVER (PARTITION BY t1.ID, Content 
                             ORDER BY DATEDIFF(d, [Validation Date], [Date])) AS rn
   FROM Table1 AS t1
   INNER JOIN Table2 AS t2 ON t1.ID = t2.ID AND [Validation Date] <= [Date] 
) t
WHERE t.rn = 1 

ROW_NUMBER()用于跟踪每个([Date][Validation Date])值对的ID - Content差异最小的记录。

答案 1 :(得分:0)

我认为这样做的唯一方法是相关性。这样的事情。

SELECT a.id, a.content, a.date,
       (SELECT TOP 1 b.value, b.validate
        FROM table2 b
        WHERE b.id=a.id
        ORDER BY b.validate DESC) from table1 a

答案 2 :(得分:0)

试试这个:

SELECT a.id, 
       a.content, 
       a.date, 
       b.valu, 
       b.validationdate 
FROM (select tt.id, 
       tt.content, 
       tt.date,
       row_number() over(partition by tt.id order by tt.date desc) rn
     from table1 tt) a
JOIN (select t.id, 
       t.content, 
       t.date, 
       t.valu, 
       t.validationdate,
       row_number() over(partition by t.id order by t.validationdate desc) rn
     from table2 t) b
on a.id=b.id and a.rn=b.rn

答案 3 :(得分:0)

我认为最好的方法是使用outer apply

select t1.id, t1.content, t1.date, t2.value, t2.validdate
from table1 t1 outer apply
     (SELECT TOP 1 t2.value, t2.validdate
        FROM table2 t2
        WHERE t2.id = t1.id
        ORDER BY t2.validdate DESC
     ) t2;