如何聚合表达式的结果?

时间:2013-08-22 15:30:00

标签: sql tsql

我想在调整docBal后获得每家公司的总和(docBal)。但是当我运行下面的查询时,我被迫在groupby中包含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

4 个答案:

答案 0 :(得分: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

这可以为您提供所需的数据,而无需在聚合函数中包含其他列。

答案 1 :(得分: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
;

答案 2 :(得分: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

答案 3 :(得分: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