2013-08-22 152 views
2

我想在調整docBal之後獲得每個公司的總和(docBal)。但是當我運行下面的查詢時,我不得不在docby中包含doctype和docbal-我不想要。我怎樣才能修改這個查詢?如何彙總表達式的結果?

select 
    DocBal = CASE d.DocType WHEN 'AD' THEN -d.DocBal 
          ELSE d.DocBal END, 
    Sum(DocBal) 
    from Vendor v 
    inner join APDoc d 
    on v.VendId = d.VendId 
    where 
     d.PerPost = 201307 
     and d.DocType in ('VO','AP','AD') 
     and d.OpenDoc = 1 
     and Acct = 210110 
    group by CpnyID 
+0

難道你不想公開'CpnyID'嗎?否則 - 如果你使用「CpnyID」分組 - 你怎麼知道哪個'SUM'屬於哪個'CpnyID'?你能否展示一些樣本數據(包括所有可能的邊緣案例)和期望的結果,所以人們不必猜測你的查詢實際上正在做什麼? –

回答

1
select sum(DocBal) FROM 
(select 
    DocBal = CASE d.DocType WHEN 'AD' THEN -d.DocBal 
          ELSE d.DocBal END, 
    CpnID 
    from Vendor v 
    inner join APDoc d 
    on v.VendId = d.VendId 
    where 
     d.PerPost = 201307 
     and d.DocType in ('VO','AP','AD') 
     and d.OpenDoc = 1 
     and Acct = 210110) a 
GROUP BY CpnID 
0
select sum(DocBal) from (
     select 
      DocBal = CASE d.DocType WHEN 'AD' THEN -d.DocBal 
            ELSE d.DocBal END, 
      CpnyID 
      from Vendor v 
      inner join APDoc d 
      on v.VendId = d.VendId 
      where 
       d.PerPost = 201307 
       and d.DocType in ('VO','AP','AD') 
       and d.OpenDoc = 1 
       and Acct = 210110 
    ) 
    group by CpnyID 
2

您可以使用子選擇捕捉您所需要的信息。

SELECT S.CpnyID, 
      SUM(S.DocBal) 
    FROM (
      SELECT CpnyID, 
        CASE d.DocType WHEN 'AD' THEN -d.DocBal ELSE d.DocBal END AS DocBal 
      FROM Vendor v 
        INNER JOIN APDoc d ON v.VendId = d.VendId 
      WHERE  d.PerPost = 201307 
      AND d.DocType in ('VO','AP','AD') 
      AND d.OpenDoc = 1 
      AND Acct = 210110 
    ) AS S 
    GROUP BY S.CpnyID 

這應該爲您提供所需的數據,而不必在聚合函數中包含額外的列。

2

你不是在說你正在使用什麼SQL產品(以及哪個版本)。這是事實,那其他人所說的派生表的解決方案將在任何產品的工作,但如果您正在使用SQL Server 2005或更高版本的工作,你也可以使用CROSS APPLY,像這樣:

SELECT 
    CpnyID, -- assuming you would like to know which SUM() belongs to which CpnyID 
    SUM(x.DocBal) 
FROM Vendor AS v 
INNER JOIN APDoc AS d ON v.VendId = d.VendId 
CROSS APPLY ( SELECT DocBal = CASE d.DocType WHEN 'AD' THEN -d.DocBal ELSE d.DocBal END ) AS x 
WHERE d.PerPost = 201307 
    AND d.DocType in ('VO','AP','AD') 
    AND d.OpenDoc = 1 
    AND Acct = 210110 
GROUP BY 
    CpnyID 
;

有在我看來,解決方案也簡單得多:你可以使整個CASE表達式成爲SUM的參數,如下所示:

SELECT 
    CpnyID, 
    SUM(CASE d.DocType WHEN 'AD' THEN -d.DocBal ELSE d.DocBal END) 
FROM Vendor AS v 
INNER JOIN APDoc AS d ON v.VendId = d.VendId 
WHERE d.PerPost = 201307 
    AND d.DocType in ('VO','AP','AD') 
    AND d.OpenDoc = 1 
    AND Acct = 210110 
GROUP BY 
    CpnyID 
;