2017-02-20 7 views
2

私は2つの異なる情報源を持っています。私はそれらを結びつけて顧客とその最後の請求書に関する情報を取得しようとしています。私は各顧客の詳細と最大請求期間の終了日を取得することができましたが、どのようにして関連する請求書から詳細を得ることができるかは不明です。私は、次のクエリがあります最新の請求書の詳細を返す

SELECT new_mprnnumber, 
     new_customernumber, 
     MAX(b.billingPeriodEndDate) as 'Billed up to date' 
FROM [CRM].[crm4_MSCRM].[dbo].[AccountExtensionBase] as a 
inner join Billing.dbo.bill as b 
    on a.new_mprnnumber = b.MPRN 
where new_accountstage = 7 
and new_accounttype = 2 
group by new_mprnnumber, 
     new_customernumber 
GO 

法案は金額によるなどのようなフィールドがありますが、私は唯一最大の日付の請求書からのものの内容を返すようにしたいと、任意の助けをいただければ幸いです

+0

使用しているdbmsにタグを付けます。 – jarlh

+0

私はSQLサーバーを使用しています – Jay

答えて

2

利用CTEとrow_number()

with CTE as 
(
select a.new_mprnnumber, 
     a.new_customernumber, 
     b.*, 
     row_number() 
     over (partition by new_customernumber -- add additional partitions as you would group bys 
       order by billingPeriodEndDate desc) as r_ord 
from AccountExtensionBase a 
inner join bill b 
    on a.new_mprnnumber = b.MPRN 
where new_accountstage = 7 
and new_accounttype = 2 
) 
select * 
from CTE 
where r_ord = 1 
1

CTEにあなたのクエリを入れた後、テーブルの法案にリンク:

WITH CTE AS (
SELECT new_mprnnumber, 
    new_customernumber, 
    MAX(b.billingPeriodEndDate) as MaxBillDate 
FROM [CRM].[crm4_MSCRM].[dbo].[AccountExtensionBase] as a 
inner join Billing.dbo.bill as b 
    on a.new_mprnnumber = b.MPRN 
where new_accountstage = 7 
and new_accounttype = 2 
group by new_mprnnumber, 
     new_customernumber 
) 
SELECT b.* 
FROM CTE c 
INNER JOIN Billing.dbo.bill b ON c.MaxBillDate = b.billingPeriodEndDate AND c.new_mprnnumber = b.MPRN 
関連する問題