1

我有闲置的更新声明:

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 中的每条记录只执行一个子查询。

我希望,有人可以帮助我解决这个问题。

4

3 回答 3

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.ArtikelAutoIDNULL没有行时,这将离开你PAYMASTER_Journal

如果您不想触摸它们,请将其更改LEFT JOININNER JOIN

于 2013-08-22T15:13:40.433 回答
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;
于 2013-08-22T15:13:08.630 回答
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
于 2013-08-22T15:21:21.230 回答