行项目SQL子查询表中的总和之和

时间:2014-05-22 17:38:55

标签: sql ms-access

我有3张桌子: 顾客 CLOSEDORDERS CLOSEDORDERARCHIVES

每个都由客户ID字段链接。 CLOSEDORDERS和CLOSEDORDERSARCHIVES是包含每张发票的每个订单项的表格。我正在努力为客户提供终生总计,但我仍坚持最后的总和。这是我写的,它为两列中的每个表输出正确的总数(一些值为空):

SELECT CUSTOMERS.Company, CUSTOMERS.[Ship City], CUSTOMERS.[Ship State], 
      (SELECT SUM (CLOSEDORDERSARCHIVE.Quantity*CLOSEDORDERSARCHIVE.SellPrice) 
      FROM CLOSEDORDERSARCHIVE 
      WHERE CLOSEDORDERSARCHIVE.CustomerID = CUSTOMERS.ID) AS archiveTotal, 
            (SELECT SUM (CLOSEDORDERS.Quantity*CLOSEDORDERS.SellPrice)
            FROM CLOSEDORDERS
            WHERE CLOSEDORDERS.CustomerID = CUSTOMERS.ID) AS currentTotal
FROM CUSTOMERS, CLOSEDORDERSARCHIVE, CLOSEDORDERS
WHERE (((CUSTOMERS.Branch)=33));

当我搜索时,我发现这个答案看起来很相似,但我无法使其工作,是因为总和是从表中的行项目求和并按客户分组的?另外,这是我的第一个查询之一,是否有更有效的方法来编写/完成此操作?

Sum of sums in different tables

2 个答案:

答案 0 :(得分:0)

我们首先可以将此问题分解为一个更简单的问题:将您需要的所有内容放在一个表格中。

如果总和所需的唯一列是数量和销售价格(以及当然的ID),您可以将它们合并到子查询中,然后计算总数。子查询看起来像:

select CustomerID as 'ID', Quantity as 'Quantity', SellPrice as 'SellPrice'
from CLOSEDORDERSARCHIVE

UNION ALL

select CustomerID as 'ID', Quantity as 'Quantity', SellPrice as 'SellPrice'
from CLOSEDORDERS

之后,您可以从该子查询中选择并按客户ID分组,然后您将获得每个客户的总计:

select ID, SUM(Quantity*SellPrice) from(

select CustomerID as 'ID', Quantity as 'Quantity', SellPrice as 'SellPrice'
from CLOSEDORDERSARCHIVE

UNION ALL

select CustomerID as 'ID', Quantity as 'Quantity', SellPrice as 'SellPrice'
from CLOSEDORDERS
) as subq1
GROUP By ID

我认为这就是你所需要的。如果您希望客户名称和类似的东西显示为=)

,您甚至可以将最后一个查询与表Customers一起加入

答案 1 :(得分:0)

我认为最不直观的解决方案是加入子查询(呃!)。这是一个(过于简单,请参见下面的警告)示例:

SELECT
  c.Company,
  c.[Ship City],
  c.[Ship State],
  co.Total + coa.Total AS 'Grand Total'
FROM CUSTOMERS c
LEFT OUTER JOIN (
  SELECT CustomerID, SUM(Quantity*SellPrice) as 'Total'
  FROM CLOSEDORDERS
  GROUP BY CustomerID
) AS 'co' ON c.ID = co.CustomerID
LEFT OUTER JOIN (
  SELECT CustomerID, SUM(Quantity*SellPrice) as 'Total'
  FROM CLOSEDORDERSARCHIVE
  GROUP BY CustomerID
) AS 'coa' ON c.ID = coa.CustomerID
WHERE c.Branch = 33

在这种情况下,我们会创建两个中间表(co和coa),它们为表中列出的每个客户提供CLOSEDORDERS和CLOSEDORDERSARCHIVE的订单总数。

警告:如果公司的CLOSEDORDERS或CLOSEDORDERSARCHIVE中没有订单,那么该公司的co.Total(或coa.Total)将为NULL。您需要检查这个或添加是错误的(IIRC NULL +数字= NULL)。所以" co.Total"和" coa.Total" SELECT子句的表达式应使用COALESCE或CASE语句来检查它。类似的东西:

...COALESCE(co.Total,0) + COALESCE(coa.Total,0) AS 'Grand Total'...