在sql server中获取上一年的记录

mbskvtky  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(919)

我需要把上一年的记录和本年的记录一起拿到
输入

id      year    amount  
----------------------
1001    2012    3747    
1001    2012    3747    
1002    2013    5746    
1002    2013    5746    
1003    2014    6756    
1003    2014    6756    
1004    2015    8746

期望输出:

id      year    amount  prevAmount
----------------------------------
1001    2012    3747    null
1001    2012    3747    null
1002    2013    5746    3747
1002    2013    5746    3747
1003    2014    6756    5746
1003    2014    6756    5746
1004    2015    8746    6756
8yoxcaq7

8yoxcaq71#

如果每一年的重复次数相同,则可以使用滞后函数:-

使用下面的db<>fiddle Create Table:- ```
create table yourtable(id int, year numeric(10), amount numeric(10));

insert into yourtable
select 1001 , 2012 , 3747 union all
select 1001 , 2012 , 3747 union all
select 1002 , 2013 , 5746 union all
select 1002 , 2013 , 5746 union all
select 1003 , 2014 , 6756 union all
select 1003 , 2014 , 6756 union all
select 1004 , 2015 , 8746;
`Fetch Data:-`
select *,LAG(amount,2) OVER(order by year) as PrevAmount from yourtable ;


### **有关更多信息,请使用此链接。

### 如果您有每年重复输入的随机数:- `Create Table:-` ```

create table yourtable(id  int,    year numeric(10),    amount numeric(10));

insert into yourtable
select 1001 ,   2012 ,  3747 union all   
select 1001 ,   2012 ,  3747 union all   
select 1001 ,   2012 ,  3747 union all
select 1002 ,   2013 ,  5746 union all   
select 1002 ,   2013 ,  5746 union all   
select 1003 ,   2014 ,  6756 union all   
select 1003 ,   2014 ,  6756 union all   
select 1004 ,   2015 ,  8746 union all
select 1004 ,   2015 ,  8746;
``` `Fetch Data:-` ```
with cte as (
select dense_rank() over(order by year) as rn1,* from yourtable
),cte1 as(
select distinct rn1+1 as rn2,* from cte
)
select cte.id,cte.year,cte.amount,cte1.amount as PrevAmount  
from cte left join cte1 on cte.rn1=cte1.rn2
yftpprvb

yftpprvb2#

如果我理解正确,你可以用 apply :

select t.*, tprev.amount
from t outer apply
     (select top (1) tprev.*
      from t tprev
      where tprev.year = t.year - 1
     );

通常,会有 order byselect top ,但这似乎对您的数据没有影响。

相关问题