从购买和销售表中减去找到的余额

时间:2017-11-11 21:07:43

标签: sql oracle subquery left-join

我有两个表:表一购买和另一个销售表,实际上我需要使用减去两个表来平衡,从表购买中减去销售额。我的代码如下:

create table purchase(
id  number(10) primary key,
name varchar2(10),
p_qty number(10)
);

并插入数据:

insert into purchase values(01,'productB',235);
insert into purchase values(04,'productC',394);
insert into purchase values(05,'productD',381);
insert into purchase values(08,'productE',357);
insert into purchase values(09,'productF',389);
insert into purchase values(10,'productQ',336);

另一张表:销售

create table  sales(
 id number(10),
 s_qty number(10),
 constraint pid_pk foreign key (id)REFERENCES purchase(id)
);

将数据插入到salse表中:

insert into sales values(01,34);
insert into sales values(04,54);
insert into sales values(05,44);
insert into sales values(09,50);
insert into sales values(01,3);
insert into sales values(04,4);
insert into sales values(05,5);
insert into sales values(09,53);
insert into sales values(01,2);
insert into sales values(04,2);
insert into sales values(05,2);
insert into sales values(09,2);
insert into sales values(01,4);
insert into sales values(04,9);
insert into sales values(05,11);
insert into sales values(09,7);

我使用了两个查询

查询1:

 select  id,name,sum(p_qty) as p_total  from purchase  group by id,name;
ID    NAME      P_TOTAL
5     productD    381
10    productQ    336
4     productC    394
1     productB    235
8     productE    357
9     productF    389

QUERY2:

select id,sum(s_qty) as s_total from sales group by id;`

ID    S_TOTAL
1     43
4     69
5     62
9     112

现在我想在桌子下方平衡每个项目

ID    NAME      P_TOTAL      S_TOTAL  BALANCE
5    productD    381          62       319
4    productC    394          69       325
1    productB    235          43       192
9    productF    389          112      277

3 个答案:

答案 0 :(得分:2)

希望这有帮助。

  SELECT p.id, p.name, p.p_total, s.s_total, 
  p.p_total - s.s_total AS balance
  FROM (select id, name, sum(p_qty) as p_total FROM purchase 
  GROUP BY id, name) p
  INNER JOIN (select id, sum(s_qty) as s_total FROM sales 
  GROUP BY id) s
  ON s.ID = p.ID;

答案 1 :(得分:0)

你几乎就在那里。获取您已经拥有的两个查询并将它们连接在一起:

SELECT p.ID,
       p.NAME,
       p.P_TOTAL,
       s.S_TOTAL,
       p.P_TOTAL - s.S_TOTAL AS BALANCE
  FROM (select id, name, sum(p_qty) as p_total
          from purchase
          group by id, name) p
  INNER JOIN (select id, sum(s_qty) as s_total
                from sales
                group by id) s
    ON s.ID = p.ID

祝你好运。

答案 2 :(得分:0)

  

我希望在桌子下方平衡每个项目

您想要每件商品的余额,但只显示销售商品的余额。

如果您想要购买的每件商品,可以将left join与子查询一起使用:

select p.id, p.name, p_total, coalesce(s_total, 0),
       (p_total - coalesce(s_total, 0)) as balance
from (select id, name, sum(p_qty) as p_total
      from purchase
      group by id,name
     ) p left join
     (select id, sum(s_qty) as s_total
      from sales
      group by id
     ) s
     on p.id = s.id;

如果您希望每件商品都有销售,那么只需使用inner join