我有一张表格,显示某一天帐户的利率。我想查询一天的利率和第二天的利率。具体来说,我正在寻找利率从一天到下一天变化的账户。
我的数据看起来像这样
帐号/贷款号码/日期/利率
1234/5656 / 1/1/18/12%
1234/5656 / 1/2/18 / 12%
1234/5656 / 1/3/18/0%
1234/5656 / 1/4/18/0%
我希望查询只返回利率从12%变为0%的两天。
根据以上数据,它将返回以下内容:
帐号/贷款号码/日期/利率/次日/次日费率
1234/5656 / 1/2/18 / 12%/ 1/3/18 / 0%
我正在使用的代码(见下文)多次返回相同的日期,并通过我无法识别的某些因素修改“次日费率”。
这是我到目前为止所拥有的。
select
tc.loanaccountid AS 'Account'
, l.LoanNumber AS 'Loan Number'
, tc.trialbalancedate AS 'Date'
, tc.interestrate AS 'Interest Rate'
, tb.trialbalancedate AS 'Next Day'
, tb.interestrate AS 'Next Day Rate'
from dbo.dailytrialbalance tc
join dbo.loanaccount l on tc.loanaccountid = l.loanaccountid
left join dbo.dailytrialbalance tb on dateadd(day, 1, tc.trialbalancedate) =
tb.trialbalancedate
where tc.PortfolioCodeId = '10'
and tc.interestrate = '0'
and tb.interestrate > '0'
我还在学习SQL,所以感谢任何帮助。谢谢。
答案 0 :(得分:0)
以下是SQL Server 2012以后的LEAD
方法。我添加了(SELECT NULL)
作为占位符,以便更正确地确定差异,因为您有1/2/18
的重复数据:
with cte as(
select
tc.loanaccountid AS 'Account'
, l.LoanNumber AS 'Loan Number'
, tc.trialbalancedate AS 'Date'
, tc.interestrate AS 'Interest Rate'
, NextDay = lead(tc.trialbalancedate) over (partition by tc.loanaccountid order by tc.trialbalancedate, (select null))
, NextDayRate = lead(tc.interestrate) over (partition by tc.loanaccountid order by tc.trialbalancedate, (select null))
from dbo.dailytrialbalance tc
join dbo.loanaccount l on tc.loanaccountid = l.loanaccountid)
select *
from cte
where NextDayRate = 0 and [Interest Rate] != 0
Here is it in action,包含您的测试数据:
declare @testData table (AccountNumber int, LoanNumber int, Date date, InterestRate varchar(3))
insert into @testData
values
(1234,5656,'20180101','12%'),
(1234,5656,'20180102','12%'),
(1234,5656,'20180103','0%'),
(1234,5656,'20180104','0%')
;with cte as(
select
AccountNumber
,LoanNumber
,[Date]
,InterestRate
,NextDay = lead([Date]) over (partition by AccountNumber order by [Date])
,NextDayRate = lead(InterestRate) over (partition by AccountNumber order by [Date])
from @testData)
select *
from cte
where NextDayRate = '0%' and InterestRate != '0%'