0

嗨,我必须在 mssql db 的一个表中合并几行。

update rashod
  set kol = (select sum(r.kol) from rashod r inner join rashod r1 on r1.k_tovar=r.k_tovar      
  where r.idnak = 2935691 and r.k_tovar=r1.k_tovar), 
    summa = (select sum(r2.summa) from rashod r2 inner join rashod r3 on r2.k_tovar=r3.k_tovar where r2.idnak = 2935691 and r2.k_tovar=r3.k_tovar)

这是一个正确的查询吗?

在表“rashod”中,几行可以具有相同的 k_tovar AND idnak。如果是这样-> 我们将这些行合并。列 kol =sum(kol),列summa=sum(summa)。这个新行保存在 db 中,所有旧行都应该删除。请帮忙。

4

2 回答 2

0

这行得通

update rashod set kol= data.kol_sum,summa=data.sum_summa
 from 
 (
    select sum(r.kol) as kol_sum,sum(r.summa)as sum_summa,r.k_tovar as k_tovar  from rashod r   
    where r.idnak = 2935691
     group by r.k_tovar
)data where rashod.k_tovar=data.k_tovar and rashod.idnak = 2935691
于 2013-10-21T08:59:49.577 回答
0

请试试这个

update rashod set kol= data.kol_sum,summa=data.sum_summa
 from 
 (
    select sum(r.kol) as kol_sum,sum(r2.summa)as sum_summa,r.k_tovar as k_tovar  from rashod r inner join rashod r1 on r1.k_tovar=r.k_tovar      
    where r.idnak = 2935691
     group by r.k_tovar,r1.k_tovar
)data where rashod.k_tovar=data.k_tovar
于 2013-10-21T06:03:30.013 回答