sql左连接给出重复的多个值

时间:2014-12-15 07:51:34

标签: sql postgresql left-join

朋友我无法获取正确的结果请建议,提前致谢。 我有两张桌子,试图获得平衡数量

一个是购买表(purchase_detail)

Pur_Date    Item_Id     Pur_Qty
2014-10-08  12792       25
2014-11-01  133263      20
2014-10-01  133263      2
2014-11-20  12792       10

其次是销售表(sale_detail)

Sale_Date   Item_Id  Sale_Qty
2014-11-17  133263     -6
2014-11-05  12792      -1
2014-11-24  133263     -2
2014-10-28  12792      -6
2014-11-05  133263     -2

使用左连接后 SQL

select a.pur_item,  sum(a.pur_qty  + b.sold_qty ) as bal_qty
from purchase_item_qty_amount  a left join  sale_item_qty_amount b 
on a.pur_item =b.sale_item  where a.pur_item IN( 12792,133263)
group by 1;

结果 - 但它不正确

Item_Id   Bal_qty 
12792     56
133263    46

结果 - 应该是

Item_Id    Bal_qty
12792      28
133263     12

3 个答案:

答案 0 :(得分:0)

尝试这个未经测试的查询:

select pur_item, sum(as bal_qty) from (
select pur_item,  sum(a.pur_qty) as bal_qty
from purchase_item_qty_amount  a
group by 1
union 
select pur_item, sum(b.sold_qty)as bal_qty
from sale_item_qty_amount b
group by 1)
group by 1

答案 1 :(得分:0)

您必须使用union而不是join,因为左侧行与右侧有多个匹配项,这会导致计算太多数据。尝试在没有总和和分组的情况下运行您的查询,以查看正在计算的原始数据,您将看到我的意思。

您的查询没有组/总和:

select a.pur_item,  a.pur_qty,  b.sold_qty from purchase_item_qty_amount  a left join  sale_item_qty_amount b on a.pur_item = b.sale_item where a.pur_item IN (12792,133263);

这是一个按预期工作的查询:

select item, sum(a.pur_qty) + sum(a.sold_qty) as bal_qty from (select pur_item as item, sum(pur_qty) as pur_qty, 0 as sold_qty from purchase_item_qty_amount where pur_item in (12792,133263) group by pur_item union select sale_item as item, 0 as pur_qty, sum(sold_qty) as sold_qty from sale_item_qty_amount where sale_item in (12792,133263) group by sale_item) a group by item;

答案 2 :(得分:0)

这是你问题的全部假人,试试这个你会得到你想要的结果: -

 purchase table

create table pt(Pur_Date date,Item_Id number, Pur_Qty number) 

insert into pt values('08.oct.2014',12792,25);
insert into pt values('01.nov.2014',133263,20);
insert into pt values('01.oct.2014',133263,2);
insert into pt values('20.nov.2014',12792,10);


 sales table

create table st(Sale_Date date , Item_Id number, Sale_Qty number)

insert into st values('17.nov.2014',133263,-6);
insert into st values('05.nov.2014',12792,-1);
insert into st values('24.nov.2014',133263,-2);
insert into st values('28.oct.2014',12792,-6);
insert into st values('05.nov.2014',133263,-2);


select purchase.Item_Id,(purchase.pur_qty+sale.sale_qty) bal_qty
from
(
 select a.Item_Id, sum(a.pur_qty) pur_qty 
 from pt  a 
 group by a.Item_Id
) purchase 
 left join 
(
 select b.Item_Id, 
 sum(b.sale_qty ) sale_qty
 from st b
 group by b.Item_Id
) sale
on sale.Item_Id = purchase.Item_Id
where purchase.Item_Id in (12792,133263)
order by 1;