给出一个金额值,例100,可以自动找出汇总成100的明细
明细表1
ID TOTAL
1 20
2 20
3 30
4 50
5 20
6 10
7 30
8 50
顺序从上往下拉,最终结算应该是这样,
ID TOTAL
1 20
2 20
3 30
5 20
6 10
明细表1
ID TOTAL
1 20
2 20
3 30
4 50
5 20
6 10
7 30
8 50
顺序从上往下拉,最终结算应该是这样,
ID TOTAL
1 20
2 20
3 30
5 20
6 10
找出的行数金额加起来是100
----------------------------------------------------------------------
CREATE
TABLE
[dbo].[Table_A](
ID
int
,TOTAL
int
)
ON
[
PRIMARY
]
GO
insert
[Table_A]
select
1,20
union
select
2,20
union
select
3,30
union
select
4,50
union
select
5,20
union
select
6, 10
union
select
7, 30
union
select
8 , 50
-- 序号连续的情况下用这种,如果不连续,可以先用row_number生个个新列
;
WITH
DEPTS
AS
(
-- 定位点成员
SELECT
ID,total,total_s = total,flag = 1
FROM
[Table_A]
where
ID = 1
UNION
ALL
-- 递归成员, 通过引用CTE自身与Dept基表JOIN实现递归
SELECT
a.ID,a.total ,total_s =
case
when
total_s + a.total > 100
then
total_s
else
total_s + a.total
end
,flag =
case
when
total_s + a.total > 100
then
0
else
1
end
FROM
[Table_A] A, DEPTS B
WHERE
A.id = B.id + 1
)
SELECT
*
FROM
DEPTS
where
flag = 1
GO
/*
1 20 20 1
2 20 40 1
3 30 70 1
5 20 90 1
6 10 100 1
*/
DROP
TABLE
[Table_A];