左连接苦苦挣扎

时间:2017-02-23 17:47:41

标签: sql left-join

我正在努力左手加入这个左联盟的最早行。

结果显示2011年的日期,但我知道这个特定行应该返回2008年。

g++ --version
g++ (Ubuntu 6.2.0-3ubuntu11~16.04) 6.2.0 20160901

以下返回正确的2008日期。

 SELECT TOP 1000 
   f.name as [Franchisee]
  ,p.paid_date as paid_date
 FROM franchisees_franchisee f
 OUTER APPLY (SELECT TOP 1 *
                FROM   era_project_invoice_payment p
                WHERE  f.franchiseeid = p.franchiseeid
                and    p.deleted = 0 and p.payment_confirmed = 1
                ORDER  BY p.eraprojectinvoicepaymentid ASC) p
where 
f.deleted = 0
and f.name LIKE '%VKlinkosch%'

问题是,我需要的不仅仅是付款表中的付费日期! :(

1 个答案:

答案 0 :(得分:1)

SELECT
    f.name as [Franchisee]
    , p.*
FROM        franchisees_franchisee  f
INNER JOIN 
(
    SELECT
        ROW_NUMBER() OVER (PARTITION BY franchiseeid ORDER BY paid_date ASC) rn
        , p.*
    FROM
        era_project_invoice_payment p
    WHERE
        deleted = 0
        AND payment_confirmed = 1
)                                   p
ON 
    f.franchiseeid = p.franchiseeid
    AND f.deleted = 0
    AND f.name LIKE '%VKlinkosch%'
    AND p.rn = 1