在同一列上将相同的表连接两次,使用不同的值仅返回最近的行

时间:2013-06-23 06:21:16

标签: mysql sql join

我试图解决一小部分复杂的JOIN问题。

我们有一个'说明'表和'估计'表。在'估计'中,对于给定指令,我们有多行用于不同类型的估计。

说明表

id | address | status
1 | 27 TAYLOR ROAD, ALBION PARK NSW 2527 | InProgress

估算表

id | instruction_id | basis | basis_date | basis_value  
1 | 1 | ContractPrice | 2012-04-05 | 124000  
2 | 1 | CAMV | 2012-02-01 | 120000  
3 | 1 | CustomerEstimate | 2012-06-07 | 132000  
4 | 1 | ContractPrice | 2013-01-03 | 140000  
5 | 1 | CustomerEstimate | 2013-02-09 | 145000

我们想要的实际上是基于instructions.id = estimate.instruction_id和estimate.basis对'估计'的2个连接加入1)最近的'CustomerEstimate'(别名basis_date和basis_value为estimate_date和estimate_value) 2)最近的'ContractPrice'(再次,将basis_date和basis_value别名为contact_date和contract_value)。

预期结果如下;

id | address | status | contract_price | contract_date | estimate_date | estimate_value  
1 | 27 TAYLOR ROAD, ALBION PARK NSW 2527 | InProgress | 2013-01-03 | 140000 | 2013-02-09 | 145000

我非常感谢那些SQL大师的帮助。

1 个答案:

答案 0 :(得分:1)

这应该有效:

SELECT *
FROM 
(
    SELECT i.id, i.address, i.status, 
        co.basis_value As contract_price, 
        co.basis_date  As contract_date,
        es.basis_date  As estimate_date, 
        es.basis_value As estimate_value,
        ROW_NUMBER() OVER(Partition By i.id Order By co.basis_date, es.basis_date) As RN
    FROM       instructions As i
    INNER JOIN estimates As co  ON (i.id = co.instruction_id AND co.basis = 'ContractPrice')
    INNER JOIN estimates As es  ON (i.id = es.instruction_id AND es.basis = 'CustomerEstimate')
) As a
WHERE RN = 1