如何在另一个连接中使用一个列?

时间:2016-05-10 11:25:44

标签: sql-server

我试图回复过去一年中最早报价是12个月内第一次报价的组织。

显然最终会使用INNER JOIN,但我仍在构建查询,从子查询开始,我想确保它正常工作。

不幸的是,我似乎遇到了一些障碍,因为我需要将JOIN的结果作为标准应用于另一个JOIN,如下所示:

表:组织

orgID | orgName
------+--------------------------
    1 | ACME Widget Corp
    2 | Widget Manufacturing, Inc

表:报价

qID | qOrgID | qDateCreated
----+--------+-------------
  1 |      1 | 2015-02-10
  2 |      1 | 2015-03-16
  3 |      2 | 2015-01-10
  4 |      2 | 2015-04-20
  5 |      2 | 2016-04-10
  6 |      1 | 2016-04-07

到目前为止我的查询。

SELECT orgID, orgName EarliestQuote, PreviousQuote
FROM Organisation
LEFT JOIN
(
    SELECT MIN(qDateCreated) AS EarliestQuote, qOrgID
    FROM 
    (
        SELECT qDateCreated, qOrgID
        FROM Quote
        WHERE qDateCreated > GETDATE() -365
    ) NewerQuotes
    GROUP BY qOrgID
) eQuotes
ON eQuotes.qOrgID = orgID
LEFT JOIN
(
    SELECT MAX(qDateCreated) AS PreviousQuote, qOrgID
    FROM 
    (
        SELECT qDateCreated, qOrgID
        FROM Quote
        WHERE qDateCreated < EarliestQuote
    ) OlderQuotes
    GROUP BY qOrgID
) pQuotes
ON pQuotes.qOrg = orgID
ORDER BY orgName

我希望得到以下数据:

orgID | orgName                   | EarliestQuote | PreviousQuote
------+---------------------------+---------------+--------------
    1 | Acme Widget Corp          | 2016-04-07    | 2015-03-16
    2 | Widget Manufacturing, Inc | 2016-04-10    | 

相反,我收到以下错误:Invalid column name 'EarliestQuote'这显然意味着我无法从一个联接中引用在另一个联接中检索的列名。

1 个答案:

答案 0 :(得分:0)

希望这会有所帮助:

;WITH Organisation AS (
SELECT *
FROM (VALUES
(1, 'ACME Widget Corp'),(2, 'Widget Manufacturing, Inc')
) as t(orgID, orgName)
), Quote AS (
SELECT *
FROM (VALUES
(1, 1, '2015-02-10'),(2, 1, '2015-03-16'),(3, 2, '2015-01-10'),
(4, 2, '2015-04-20'),(5, 2, '2016-04-10'),(6, 1, '2016-04-07')
) as t(qID, qOrgID, qDateCreated)
)
, cte AS (
SELECT  o.orgID, 
        o.orgName,
        q.qDateCreated,
        DENSE_RANK() OVER (PARTITION BY o.orgID, o.orgName ORDER BY q.qDateCreated) as dr
FROM Organisation o
INNER JOIN Quote q 
    ON q.qOrgID = o.orgID
)

SELECT  c.orgID,
        c.orgName,
        MAX(c.qDateCreated) as EarliestQuote,
        MAX(c1.qDateCreated) as PreviousQuote
FROM cte c
LEFT JOIN cte c1 
    ON c.orgID = c1.orgID AND DATEDIFF(month,c1.qDateCreated,c.qDateCreated) > 12 AND c.dr - c1.dr = 1
GROUP BY c.orgID,
        c.orgName

输出:

orgID       orgName                   EarliestQuote PreviousQuote
----------- ------------------------- ------------- -------------
1           ACME Widget Corp          2016-04-07    2015-03-16
2           Widget Manufacturing, Inc 2016-04-10    NULL