您好我必须在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和idnak。如果是的话 - >我们统一这些行。列kol =sum(kol)
,列summa=sum(summa)
。这个新行保存在db中,应删除所有旧行。
请帮助。
答案 0 :(得分: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
答案 1 :(得分: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