[code=sql]nnWITH t (用户 ,类型, 金额 ) ASn(select 'A','存入',100 UNION ALL nselect 'A','存入', 200 UNION ALL nselect 'A','取出', 100 UNION ALL nselect 'A', '取出', 200 UNION ALL nselect 'A','存入' ,300 UNION ALL nselect 'A','取出', 300 )n,t1 asn(SELECT * ,ROW_NUMBER() OVER (ORDER BY 用户 )AS row1 FROM t )n,t2 AS n(SELECT *,ROW_NUMBER() OVER (ORDER BY row1 )+1 AS row2 FROM t1)n,t3 AS (SELECT * ,金额1=CASE 类型 WHEN '存入' THEN 金额 ELSE -金额 end FROM t2)nSELECT *, (SELECT SUM(金额1) FROM t3 n WHERE n.row1< w.row2 ) AS 余额 FROM t3 AS w[/code]
Re: bkq4215115856小时前
回复Myuen亲,如果有1000条数据,难不成要写1000个select???
2楼F172515968昨天 10:34
select 用户 as 用户, sum(金额) as 余额 from (select 用户 as 用户,金额 as 金额 from tb where 类型号‘存入’ union all select 用户 as 用户,-金额as 金额 from tb where 类型号‘取出’ ) t group by 用户