如何从主查询中的子查询中检索值?

时间:2019-06-11 20:01:33

标签: sql sql-server

我想在主查询中检索dtmPost。我在ai.strID之后尝试了a.dtmPost,但是没有用。我不确定如果不做大的改动是否可以这样做。我的假设正确吗?

SELECT  p.strMed,
    d.lngAKey,
    ai.strID

FROM    tblP p RIGHT JOIN tblV v 
ON  p.lngPKey  = v.lngPKey INNER JOIN tblD d 
ON  v.lngVKey  = d.lngVKey INNER JOIN tblAI ai
ON  d.lngAKey = ai.lngAKey

WHERE   dtmEff between

    (SELECT MAX(a.dtmPost) AS dtmPost

    FROM    (SELECT dtmPost 
        FROM    tblPBIH pbih 
        WHERE   pbih.lngAKey    = d.lngAKey 

        UNION   

        SELECT  dtmPost 
        FROM    tblPBI pbi 
        WHERE   pbi.lngAKey     = d.lngAKey 
        ) a)

AND (SELECT MAX(a.dtmPost) AS dtmPost 

    FROM    (SELECT DATEADD(D, 10, pbih.dtmPost) AS dtmPost 
        FROM    tblPBIH pbih 
        WHERE   pbih.lngAKey    = d.lngAKey 

        UNION   

        SELECT  DATEADD(D, 10, pbi.dtmPost) AS dtmPost 
        FROM    tblPBI pbi 
        WHERE   pbi.lngAKey     = d.lngAKey 
        ) a)

我想出了以下方法,它可以工作,但是还有其他更好的方法吗?

DECLARE @X date, @Y date

SET @X =(SELECT MAX(a.dtmPost) AS dtmPost

    FROM    (SELECT dtmPost 
        FROM    tblPBIH pbih 
        WHERE   pbih.lngAKey    = d.lngAKey 

        UNION   

        SELECT  dtmPost 
        FROM    tblPBI pbi 
        WHERE   pbi.lngAKey     = d.lngAKey 
        ) a)

SET @Y =(SELECT MAX(a.dtmPost) AS dtmPost 

    FROM    (SELECT DATEADD(D, 10, pbih.dtmPost) AS dtmPost 
        FROM    tblPBIH pbih 
        WHERE   pbih.lngAKey    = d.lngAKey 

        UNION   

        SELECT  DATEADD(D, 10, pbi.dtmPost) AS dtmPost 
        FROM    tblPBI pbi 
        WHERE   pbi.lngAKey     = d.lngAKey 
        ) a)

SELECT  p.strMed,
    d.lngAKey,
    ai.strID,
    @X AS dtmBackDate

FROM    tblP p RIGHT JOIN tblV v 
ON  p.lngPKey  = v.lngPKey INNER JOIN tblD d 
ON  v.lngVKey  = d.lngVKey INNER JOIN tblAI ai
ON  d.lngAKey = ai.lngAKey

WHERE   dtmEff > @X
AND     dtmEff <= @Y

感谢您的所有帮助。

1 个答案:

答案 0 :(得分:1)

从我看到的两个日期之间唯一的区别是10天,因此绝对没有理由重复两次查询。

这是重做的查询版本。由于我们没有测试数据,因此我不知道是否有错别字,但您应该明白这一点。如果愿意,还可以使用CTE编写它。

我也将您的右连接替换为左连接,因为我个人从不使用右连接,但这可能只是个人喜好。

SELECT  p.strMed,
    d.lngAKey,
    ai.strID,
    dates.dtmPost AS dtmBackDate
FROM tblV v  
INNER JOIN tblD d ON  v.lngVKey  = d.lngVKey 
INNER JOIN tblAI ai ON  d.lngAKey = ai.lngAKey
LEFT JOIN tblP p ON  p.lngPKey  = v.lngPKey
INNER JOIN (
        select  lngAKey, max(dtmPost) dtmPost from 
        (
            SELECT  lngAKey, dtmPost 
            FROM    tblPBIH pbih 
            WHERE   pbih.lngAKey

            UNION   

            SELECT  lngAKey, dtmPost 
            FROM    tblPBI pbi 
            WHERE   pbi.lngAKey
        ) q
        group by lngAKey
        ) dates on dates.lngAKey=d.lngAKey
WHERE   dtmEff > dates.dtmPost
AND     dtmEff <= DATEADD(D, 10, dates.dtmPost)