我有更新的声明:
update tmp set
tmp.Anzahl=(select sum(a.BNANZ) from PAYMASTER_Journal a where a.BNARTID=tmp.ArtikelAutoID),
tmp.Betrag=(select sum(a.BNBETR) from PAYMASTER_Journal a where a.BNARTID=tmp.ArtikelAutoID),
tmp.Rabatt=(select sum(a.BNRMRBETR) from PAYMASTER_Journal a where a.BNARTID=tmp.ArtikelAutoID)
from ##tmp1 tmp
这样,对于## tmp1中的每条记录,执行了3个子查询。 ## tmp1包含10'000条记录 - >总共30'000个子查询。
因为每个子查询从PAYMASTER_Journal中选择相同的记录,所以我正在寻找一种方法,在## tmp1中每个记录只执行一个子查询来更新## tmp1。
我希望,有人可以帮我解决这个问题。
答案 0 :(得分:1)
使用LEFT JOIN
试试这个
update tmp set
tmp.Anzahl=BNANZ_accumulated,
tmp.Betrag=BNBETR_accumulated,
tmp.Rabatt=BNRMRBETR_accumulated
from ##tmp1 tmp
LEFT JOIN ( SELECT BNARTID,
SUM(BNANZ) AS BNANZ_accumulated,
SUM(BNBETR) AS BNBETR_accumulated,
SUM(BNRMRBETR) AS BNRMRBETR_accumulated
FROM PAYMASTER_Journal
WHERE (ARTIKELAUSWAHL=0x30 AND BLBONSTO=0x30 AND BLZESTO=0x30 AND
STORNO=0x30 AND
BDDAT BETWEEN '20120301' AND '20130821' AND
AdressID='d68e4d8f-e60e-4482-9730-76076948df43' AND
BNFIL=5 AND
ISNULL(Preisliste, 'VK-Preisliste') = 'VK-Preisliste' AND
BNARTID=tmp.ArtikelAutoID)
GROUP BY BNARTID) a ON a.BNARTID=tmp.ArtikelAutoID
如果给定的## tmp1.ArtikelAutoID
NULL
中没有行,将离开PAYMASTER_Journal
如果您不想触摸它们,请将LEFT JOIN
更改为INNER JOIN
答案 1 :(得分:0)
我会选择MERGE
声明:
merge ##tmp1
using (select
BNARTID
,sum(BNANZ) as BNANZ
,sum(BNBETR) as BNBETR
,sum(BNRMRBETR) as BNRMRBETR
from
PAYMASTER_Journal
group by
BNARTID
) as upd
on tmp.ArtikelAutoID = upd.BNARTID
when matched then update set Anzahl=BNANZ, Betrag=BNBETR, Rabatt=BNRMRBETR;
答案 2 :(得分:0)
您可以使用单个子查询执行此操作。
UPDATE tmp T
INNER JOIN
(SELECT a.BNARTID
,sum(a.BNANZ) as BANAZ_SUM
,sum(a.BNBETR) as BNBETR_SUM
,sum(a.BNRMRBETR) as BNRMRBETR_SUM
FROM PAYMASTER_Journal a
WHERE a.BNARTID = tmp.ArtikelAutoID
GROUP BY
a.BNARTID
) SQ
ON SQ.BNARTID = tmp.ArtikelAutoID
SET tmp.Anzahl = SQ.BANAZ_SUM
,tmp.Betrag = SQ.BNBETR_SUM
,tmp.Rabatt = SQ.BNRMRBETR_SUM