SQL前后相减、累计求和、多行合并

测试数据

with tb as(
select 1 id,25 qty
union all select 2,30
union all select 3,67
union all select 4,17
)

前后相减

select *,(select a.qty-b.qty from tb b where a.id=b.id+1) 差
from tb a

迭代求和

select *,(select sum(qty) from tb b where b.id<=a.id) 和
from tb a

多行合并

select stuff((select ','+cast(qty as varchar) from tb order by qty for xml path('')),1,1,'')




你可能感兴趣的:(数据库)