选择最接近另一个日期的日期

时间:2017-01-27 14:18:43

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

我正在查询表格(COURSEPLACE)以生成学生的结果集。这包含从课程表中获取的一系列变量。

然后我想加入一个地址表(每个学生包含多个地址记录),但只在结果中附加在创建学生记录的日期相同(或最近)日期创建的1个邮政编码

我尝试的是以下内容,但这只能获取那些日期值完全匹配的记录 - 如何将其扩展为(有效地)查找并从具有以下内容的地址记录中选择邮政编码值最接近学生记录日期戳的日期戳?:

SELECT cp.CONTACTNO, cp.AGEONENTRY, cp.COURSETITLE, cp.FACULTY, ad.POSTCODE
FROM COURSEPLACE cp
LEFT OUTER JOIN ADDRESS ad ON ad.CONTACTNO=cp.CONTACTNO
WHERE 
cp.TYPE = 'Application'
AND cp.TERM = '2015/6'
AND 
(
ad.TYPE = 'Home' AND CONVERT(VARCHAR(23),ad.CREATIONDATE,103) = CONVERT(VARCHAR(23),cp.CREATIONDATE,103)
)

3 个答案:

答案 0 :(得分:0)

使用OUTER APPLY解决它,作为对上一个问题的回答:

OUTER APPLY (SELECT TOP 1 *  FROM ADDRESS ad2 WHERE  ad2.CONTACTNO=cp.CONTACTNO ORDER BY DATEDIFF(dd,cp.CREATIONDATE,ad2.CREATIONDATE)) AD

答案 1 :(得分:0)

给它一个旋转......

SELECT cp.CONTACTNO, cp.AGEONENTRY, cp.COURSETITLE, cp.FACULTY, ad.POSTCODE
FROM COURSEPLACE cp
LEFT JOIN ADDRESS ad ON 
    ad.CONTACTNO=cp.CONTACTNO
    INNER JOIN
    (SELECT CONTACTNO, MAX(CREATIONDATE) dt 
    FROM ADDRESS
    WHERE CREATIONDATE <= cp.CREATIONDATE
    GROUP BY CONTACTNO) ad2 on ad2.dt = ad.CREATIONDATE and ad2.CONTACTNO = ad.CONTACTNO
WHERE 
cp.TYPE = 'Application'
AND cp.TERM = '2015/6'

答案 2 :(得分:0)

SELECT TOP 1
    cp.CONTACTNO, cp.AGEONENTRY, cp.COURSETITLE, cp.FACULTY, ad.POSTCODE,
FROM 
    COURSEPLACE cp
    INNER JOIN ADDRESS ad ON ad.CONTACTNO=cp.CONTACTNO
WHERE CP.TYPE = 'Application'
    AND CP.TERM = '2016/5'
    AND AD.TYPE = 'Home'
ORDER BY 
    DATEDIFF(AD.CREATIONDATE, CP.CREATIONDATE) ASC;