需要SQL查询将上个月的值与月度值相对应。
约束:不要使用任何LAG,OVER,PARTITION,Row_number()等。仅使用LEFT,RIGHT或INNER连接并实现它。
我有一张表如下
LoanID1 Jan 2000 LoanID1 Feb 3000 LoanID1 March 2500 LoanID1 April 1000 LoanID1 May 500 LoanID2 Jan 750 LoanID2 FEB 3500 LoanID2 March 2700 LoanID2 April 1500 LoanID2 May 4000
基本上,这些是每个LoanID的月度值,我需要的是我需要另一个列具有上个月的值,如下表所示:
LoanID1 Jan 2000
LoanID1 Feb 3000 2000
LoanID1 March 2500 3000
LoanID1 April 1000 2500
LoanID1 May 500 1000
LoanID2 Jan 750
LoanID2 FEB 3500 750
LoanID2 March 2700 3500
LoanID2 April 1500 2700
LoanID2 May 4000 1500
我试过加入同一张桌子却无法实现。请指导我并告诉我一些如何做到这一点。
更新以提供实际细节:
插图图像:实际数据如何可用以及我在第二张图像中需要它
[这是具有记录的实际数据库
这是我需要的另一个专栏(上个月的价值观)
提前感谢您的指导和感谢。
答案 0 :(得分:0)
根据您使用的RDBMS,您需要添加按日期排序的“行号”列,您可以根据该列执行连接。 它看起来像这样
select
t1.month,
t1.value as curr_mon_val,
t2.value as prev_mon_val
from
(select t1.month, t1.value, row_number from t1) as t1
join (select t1.value, row_number from t1 where row_number > 1) as t2
on t1.row_number = t2.row_number-1
这是您需要编写的内容的近似值,具体取决于您的RDBMS
答案 1 :(得分:0)
您可以使用LAG功能
来完成此操作 declare @myt table (id nvarchar(50),monthnames nvarchar(50),amount int)
insert into @myt
values
('LoanID1','Jan', 2000 ),
('LoanID1','Feb', 3000 ),
('LoanID1','March', 2500 ),
('LoanID1','April', 1000 ),
('LoanID1','May', 500 ),
('LoanID2','Jan', 750 ),
('LoanID2','Feb', 3500 ),
('LoanID2','March', 2700 ),
('LoanID2','April', 1500 ),
('LoanID2','May', 4000 )
select *,LAG(Amount,1,0) Over(partition by ID order by id,MonthNumber) as PreviousMonth from (
select *,Month(cast(monthnames+'1 2018' as date)) as MonthNumber from @myt
)x