2017-02-23 135 views
0

我在左連接左連接中最早的一行掙扎。與左連接奮鬥

結果顯示2011年的日期,但我知道一個事實,這個特定的行應該返回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%' 

下面返回正確的,2008年的日期。

SELECT TOP 1000 
    f.name as [Franchisee] 
    ,min(p.paid_date) as paid_date 
from [era_uat_shared].[dbo].[franchisees_franchisee] f 
left join era_project_invoice_payment p 
on f.franchiseeid = p.franchiseeid 
where f.deleted = 0 
and f.name LIKE '%VKlinkosch%' 
GROUP BY f.name 

問題是,我需要的不僅僅是支付表中的付費日期! :(

+0

我會仔細檢查你的事實...... 2008年的日期不是那個'franchseeid',或'deleted'不等於'0',或者'payment_confirmed'不等於' 1'。 – SqlZim

+0

也許它沒有按照你期望的內部視圖排序? – user1327961

+0

Hi Zim,2008指的是付費日期。爲了得到這個2008年的日期,我所要做的就是使用min(paid_date)和在一個小小的查詢中的f.name字段 – Justin

回答

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 
+0

這傢伙是老闆。 :) – Justin