请问,如何将dbo.Clicks中的同一CodeID的Clicks的值求和,并插入到dbo.BusCode表中对应CodeID的Views中,如果Views中已经有值,把那个和跟这个旧值相加,插入到Views中
最好能用update命令一句话执行
3 个解决方案
#1
--更新
;with cte as(
select codeid as cid,sum(clicks) as csum from dbo.clicks
group by codeid
)
update dbo.BusCode set views=views+csum from cte where codeid=cid
#2
update dbo.BusCode
set views=views+csum
from
(
select codeid,sum(clicks) as csum
from dbo.clicks
group by codeid
)t
where t.codeid= BusCode.codeid
#3
你这个本来就是更新,不是插入
UPDATE dbo.BusCode
SET dbo.BusCode.VIEWS=dbo.BusCode.VIEWS+b.clicks
FROM (
SELECT codeid,SUM(clicks)clicks
FROM dbo.Clicks
GROUP BY codeid)b
WHERE dbo.BusCode.codeid=b.codeid
#1
--更新
;with cte as(
select codeid as cid,sum(clicks) as csum from dbo.clicks
group by codeid
)
update dbo.BusCode set views=views+csum from cte where codeid=cid
#2
update dbo.BusCode
set views=views+csum
from
(
select codeid,sum(clicks) as csum
from dbo.clicks
group by codeid
)t
where t.codeid= BusCode.codeid
#3
你这个本来就是更新,不是插入
UPDATE dbo.BusCode
SET dbo.BusCode.VIEWS=dbo.BusCode.VIEWS+b.clicks
FROM (
SELECT codeid,SUM(clicks)clicks
FROM dbo.Clicks
GROUP BY codeid)b
WHERE dbo.BusCode.codeid=b.codeid