求和问题-不给出单独的行总和,显示每行的总和

时间:2019-07-05 09:32:17

标签: sql tsql

我正试图合并两个报告,以根据匹配的客户编号,订单号和产品代码查找总运费,重量和美元金额。我最初是对每个客户编号,订单编号,产品代码,重量和美元金额组合的运费进行汇总。但是由于某种原因,它会为每个重量和美元金额重复一个客户编号/订单编号/产品代码的总和,我不知道为什么。

我尝试更改基本上每种可能的组合中要累加的列,但是如果我将重量和美元相加,则货运是正确的,而重量和美元金额则是错误的。如果我将运费加在一起,则运费是错误的,但重量和美元是正确的。

    SELECT a.cust, a.order_num, a.prod_code, a.WEIGHT as weight, a.AMOUNT as amount, SUM(b.AMOUNT) as freight_amt
    from dbo.[report1] a
    join dbo.[report2] b on a.cust = b.cust and a.order_num = b.order_num and a.prod_code = b.product and a.loc = b.loc
    where a.order_num = '149254'
    group by a.cust, a.order_num, a.prod_code, a.WEIGHT, a.AMOUNT

我期望的是: 客户A,订单号123,产品代码456的重量为10,重量为200,运费为76

客户A,订单号789,产品代码456的重量为15,数量为150,运费为90

我的查询当前显示的方式是: 客户A,订单号123,产品代码456的重量为10,重量为200,运费为166

客户A,订单号789,产品代码456的重量为15,数量为150,运费为166

对此感到困惑,我深表歉意。根据公司政策,我无法提供我正在使用的任何实际数据或真实的列名,因此,这是我目前能做的最好的事情。预先感谢。

1 个答案:

答案 0 :(得分:1)

我猜你想要union allgroup by

select cust, order_num, prod_code, loc,
       sum(weight),  -- I'm not sure if this should be sum() or max()
       sum(amount), sum(freight_amt)
from ((select cust, order_num, prod_code, loc,
              weight, amount,
              null as freight_amt
       from dbo.report1
      ) union all
      (select cust, order_num, product, loc,
              null as weight, null as amount,
              null as freight_amt
       from dbo.report1
      )
     ) rr
group by cust, order_num, prod_code, loc