当连接两个表时,Sum似乎是双倍/三倍计数

时间:2014-07-22 16:35:52

标签: sql sql-server join sum left-join

我正在尝试在标识号上加入两个表(库存和销售),并将库存中的货物数量,库存值和销售价值/数量相加。这是按部件号分组的。

这就是我正在做的事情:

`select inv.[num]
, sum(inv.[Value]) as [Inventory Value]
, sum(inv.[qty]) as [Inventory Qty]
, sum(sales.[Value]) as [Sales Value]
, sum(sales.[qty]) as [Sales qty]
from Inv
left join sales
on inv.[num]=sales.[num]
group by inv.[num]`

库存价值总和约为50倍,销售额约为3或4倍。 我如何避免过度总结?

1 个答案:

答案 0 :(得分:0)

group by与多对一或多对多联接一起使用时,您应首先汇总度量并加入维度。

select
    inv_agg.inv_num as 'Inventory Number'
    ,inv_agg.inv_value as 'Inventory Value'
    ,inv_agg.inv_qty as 'Inventory Qty'
    ,sales_agg.sales_value as 'Sales Value'
    ,sales_agg.sales_qty as 'Sales Qty'
from (select 
        inv.num as inv_num
        ,sum(inv.Value) as inv_value
        ,sum(inv.qty) as inv_qty
    from inv
    group by inv.num) inv_agg
left join (select
        sales.num sales_num
        ,sum(sales.Value) as sales_value
        ,sum(sales.qty) as sales_qty
    from sales
    group by sales.num) sales_agg
on inv_agg.inv_num = sales_agg.sales_num

或者,使用CTE'

with inv_agg as (select 
        inv.num as inv_num
        ,sum(inv.Value) as inv_value
        ,sum(inv.qty) as inv_qty
    from inv
    group by inv.num),
sales_agg as (select
        sales.num sales_num
        ,sum(sales.Value) as sales_value
        ,sum(sales.qty) as sales_qty
    from sales
    group by sales.num)
select
    inv_agg.inv_num as 'Inventory Number'
    ,inv_agg.inv_value as 'Inventory Value'
    ,inv_agg.inv_qty as 'Inventory Qty'
    ,sales_agg.sales_value as 'Sales Value'
    ,sales_agg.sales_qty as 'Sales Qty'
from inv_agg left join sales_agg
    on inv_agg.inv_num = sales_agg.sales_num