返回与用户关联的最新帐单的详细信息

时间:2017-02-20 14:47:36

标签: sql sql-server join max

我有两种不同的信息来源,我试图将它们结合在一起,以获取有关客户及其最后账单的信息。我已设法获取每个客户的详细信息及其最长结算期限结束日期,但我不确定如何从相关账单中获取详细信息。我有以下查询:

set.seed(123)
df <- data.frame(v1 = c(rep("A", 3), rep("B", 3)),
                 v2 = c(rep(letters[1:3], 2)),
                 dfA = sample(1:10, 6),
                 dfB = sample(1:10, 6),
                 dfC = sample(1:10, 6))

该法案有像应付金额等字段,但我只想从最大日期法案中返回那些细节,任何帮助都将不胜感激

2 个答案:

答案 0 :(得分:2)

使用row_number()

的CTE
{{1}}

答案 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