22,210
社区成员
发帖
与我相关
我的任务
分享
CREATE TABLE #Temp(
ID int,
Price numeric(18,4),
)
Insert Into #Temp(ID,Price)
Select 1 as ID, 20 as Price
Union All
Select 2 as ID, 15 as Price
Union All
Select 3 as ID, 10 as Price
Union All
Select 4 as ID, 20 as Price
Union All
Select 5 as ID, 25 as Price
Union All
Select 6 as ID, 50 as Price
Union All
Select 7 as ID, 40 as Price
Union All
Select 8 as ID, 20 as Price
--想取出指定Price汇总值达到某个数字后的记录,记录可以是随机的,
--例如金额达到100之后的记录,记录只要按照排序规则取前面的若干条记录即可,
--例如本案例按照ID排列,取前面的6条即可满足我的要求
--目的是取出最后一条记录我要用来拆分出不同的支付方式
Select * From #Temp
Drop Table #Temp
select ID,price,(select SUM(Price) from #Temp where ID<=t.ID) as total
from #Temp t
CREATE TABLE #Temp(
ID int,
Price int,
)
Insert Into #Temp(ID,Price)
Select 1 as ID, 20 as Price
Union All
Select 2 as ID, 15 as Price
Union All
Select 3 as ID, 10 as Price
Union All
Select 4 as ID, 20 as Price
Union All
Select 5 as ID, 25 as Price
Union All
Select 6 as ID, 50 as Price
Union All
Select 7 as ID, 40 as Price
Union All
Select 8 as ID, 20 as Price
;
with cte as
(
select ID,price,Price as Total from #Temp
where ID=1
union all
select t.ID,t.price,t.Price+cte.Total from #Temp t join cte on t.ID=cte.ID+1
)
select * from cte where ID<=(select top 1 ID from cte where Total>100)
drop table #Temp
CREATE TABLE #Temp(
ID int,
Price numeric(18,4),
)
Insert Into #Temp(ID,Price)
Select 1 as ID, 20 as Price
Union All
Select 2 as ID, 15 as Price
Union All
Select 3 as ID, 10 as Price
Union All
Select 4 as ID, 20 as Price
Union All
Select 5 as ID, 25 as Price
Union All
Select 6 as ID, 50 as Price
Union All
Select 7 as ID, 40 as Price
Union All
Select 8 as ID, 20 as Price
--想取出指定Price汇总值达到某个数字后的记录,记录可以是随机的,
--例如金额达到100之后的记录,记录只要按照排序规则取前面的若干条记录即可,
--例如本案例按照ID排列,取前面的6条即可满足我的要求
--目的是取出最后一条记录我要用来拆分出不同的支付方式
Select * From #Temp
declare @cmoney numeric(18,4),@pricesum numeric(18,4)
declare @i int, --loop counter;
@topN int, --returns top n numbers
@max int --returns loops max value
select @i=1, @topN=0, @max=0,@cmoney =100,@pricesum=0
while @i< (select MAX(id) from #Temp)
begin
select @pricesum =@pricesum+price from #Temp where ID = @i
IF @cmoney <@pricesum
begin
set @topN = @i
break
end
SET @i= @i+1
end
select * from #Temp where ID <= @topN
Drop Table #Temp
ID Price
1 20.0000
2 15.0000
3 10.0000
4 20.0000
5 25.0000
6 50.0000