如何从1行获取查询值以使用到另一行?

rif*_*nan 5 sql database stored-procedures sql-server-2008

这是示例查询:

payment_Type    payment_value       cost_type      cost value
Cost I          100                 Registration       40
Cost I          100                 books              40
Cost I          100                 Lab                40
Run Code Online (Sandbox Code Playgroud)

COST我有3个要素Cost_Type是有自己的Cost_value.

我想像这样操纵:

payment_Type    payment_value       cost_type      cost value     Payment_by_cost_type
Cost I          100                 Registration       40              40
Cost I          100                 books              40              40
Cost I          100                 Lab                40              20
Run Code Online (Sandbox Code Playgroud)

关键是我想把它分成payment_value每一个cost_value.在该示例中,payment_by_cost变为40,40,20 = 100.

实验室cost_value是40但它可以分配值为20,因为仍然是上面划分的2成本类型.

我可以使用Payment_by_cost_type下一行记录中的值吗?我一直在尝试将值插入Payment_by_cost_type临时表,但select不能有insert语句.

有没有人对如何解决这个问题有任何想法?我一直在咨询DWH,他说必须使用Store程序才能通过查询完成.

val*_*lex 2

我猜您的表不仅包含“Cost I”,还包含其他值,因此这里是一个查询,用于输出表中所有组(按 Payment_type)的结果:

;with table1 as
(select 
t.*,
row_number() 
 OVER 
(PARTITION BY payment_Type order by cost_type) rn
from t
)
,table2 as
( select t4.*,isnull((select sum(cost_value) from table1 
    where table1.payment_type=t4.payment_type and rn<t4.rn),0) CumSum 
  from table1 t4
) 
select payment_type,payment_value,cost_type,cost_value,
case when cost_value+CumSum<=payment_value then cost_value
  else 
    payment_value-Cumsum                  
  end                     

from table2
order by Payment_type,rn;
Run Code Online (Sandbox Code Playgroud)

SQLFIDDLE演示