汇总库存中的所有价值(数量),然后加入并汇总客户(数量)表的所有价值并显示为另一列为available_stock

时间:2018-02-22 15:00:38

标签: sql sql-server sql-server-2008

sum函数结果不正确(连接两个表时)##

select dress,sum(qty) as sold 
 from customer group by dress
-----------------------
Dress         |  Sold |
Casual Dress  |  5    |
Fancy Dress   |  2    |
Jeans         |  3    |
-----------------------

- 正确的结果

select dress,sum(qty) as stock 
from stock group by dress
-----------------------
Dress         |  Stock |
Casual Dress  |  15    |
Fancy Dress   |  17    |
Jeans         |  35    |
Party Wear    |  15    |
-----------------------

- 正确的结果

加入两个表

    select s.Id ,s.dress, sum(s.qty) 
    as stock, sum(c.qty) as sold,
    sum(s.qty-c.qty) as available
    from stock s
    left outer join customer c
    on c.Id=s.Id group by s.dress,s.Id

----------------------------------------------
Id  Dress        | Stock | Sold | available  |
1   Fancy Dress  | 17    | 6    | 11         | 
2   Casual Dress | 30    | 10   | 20         |
3   Party Wear   | 15    | NULL | NULL       |
4   Jeans        | 35    | 18   | 17         |
----------------------------------------------
加入上表

时,

结果不正确

2 个答案:

答案 0 :(得分:0)

我建议使用带有productId和productName的产品表进行更好的数据库设计。但是,根据您提供的内容

create table #customer
(
    customerId      int
    ,dressName      varchar(20)
    ,qtySold        int
)

create table #dress
(
    dressId     int 
    ,dressName  varchar(20)
    ,qtyInStock int
)

insert into #customer
select 1,'Casual Dress',5 union all
select 1,'Casual Dress',5 union all
select 1,'Fancy Dress',2 union all
select 2,'Jeans',3

insert into #dress
select 1,'Casual Dress',15 union all
select 2,'Fancy Dress',17 union all
select 3,'Jeans',35 union all
select 4,'Casual Dress',15 union all
select 5,'Party Wear',15 

select * from #customer
select * from #dress

select t2.dressName, t2.stock, t1.sold, (t2.stock - t1.sold) as available 
from
    (select dressName, sum(qtySold) as sold
     from #customer
     group by dressName) t1
     right join (select dressName, sum(qtyInStock) as stock
            from #dress
            group by dressName) t2 on t1.dressName = t2.dressName


 drop table #customer
 drop table #dress

ouptput:

dressName       stock   sold    available
Casual Dress    30      10      20
Fancy Dress     17      2       15
Jeans           35      3       32
Party Wear      15      NULL    NULL

答案 1 :(得分:0)

我尝试使用您的数据重现您的情况(根据2个正确的查询结果)但没有发生任何错误

http://sqlfiddle.com/#!18/9eecb/4208

我怀疑你在每张桌子上有相同产品的不同ID,所以你可以尝试加入你的桌子上的衣服(名字)而不是ids