在SQL Server中使用联接的正确方法

时间:2018-12-29 00:57:04

标签: sql sql-server tsql

我的数据库中有四个表,如下所示:

  1. Transactions用于区分购买和销售交易
  2. Products中维护产品详细信息
  3. Stocks用于维护产品数量
  4. BillDetails用于维护PurchaseSales

enter image description here

我确实尝试过使用界面进行买卖操作,并且它可以正常工作 但是我在使用SQL Server联接向我显示这三个表中的数据时遇到了问题(我从哪个产品中购买了多少,以及从中购买了多少)。

我尝试的代码如下。

select 
    pro_ID
    , sum(case when trn_type = 'PRCH' then stk_quantity else 0 end) as stock
    , sum(case when trn_type = 'PRCH' then bdt_quantity else 0 end) as purchase
    , sum(case when trn_type = 'SALE' then bdt_quantity else 0 end) as Sale
    , sum(case when trn_type = 'PRCH' then bdt_quantity else 0 end)-(sum(case 
        when trn_type = 'PRCH' then bdt_quantity else 0 end)- sum(case when 
        trn_type = 'SALE' then bdt_quantity else 0 end)) as diff
from 
    stocks
join 
    Products on Products.pro_ID = Stocks.stk_Product
right outer join 
    BillDetails on Products.pro_iD = BillDetails.bdt_Product
join 
    Transactions on BillDetails.bdt_trnRef = Transactions.trn_Reference
where 
    pro_ID = '6260100600362'
group by 
    pro_ID 
order by 
    pro_ID asc

由于我只售出上述产品之一,但我的查询却给我错误的销售和购买结果,如以下屏幕截图所示。

enter image description here

基于表信息,正确的信息或结果应类似于以下内容。

  1. 股票= 123
  2. 购买= 124
  3. 销售= 1
  4. 差异= 1

1 个答案:

答案 0 :(得分:0)

这里的问题是您使用库存表作为基础表。在基表中,您有两个用于相同proID / stk_product的条目。然后,无论何时使用此ID上的条件进行联接,您之后在联接表上都会有两个条目具有相同的值。因此,求和后,您的价值将翻倍。

我建议您使用product作为基表,然后进行联接。

您可以尝试以下方法:

with stocks as (
    select 
        Stk_trnref
        , stk_Product
        , sum(stk_quantity) stk_quantity
    group by Stk_trnref, stk_Product
),

select 
  stk_Product
  , sum(case when trn_type = 'PRCH' then stk_quantity else 0 end) as stock
  , sum(case when trn_type = 'PRCH' then bdt_quantity else 0 end) as purchase
  , sum(case when trn_type = 'SALE' then bdt_quantity else 0 end) as Sale
  , sum(case when trn_type = 'PRCH' then bdt_quantity else 0 end)-(sum(case 
    when trn_type = 'PRCH' then bdt_quantity else 0 end)- sum(case when 
    trn_type = 'SALE' then bdt_quantity else 0 end)) as diff
from Products
left join stocks on Products.pro_ID = Stocks.stk_Product
left join BillDetails on Products.pro_iD = BillDetails.bdt_Product
left join Transactions on BillDetails.bdt_trnRef = Transactions.trn_Reference
where pro_ID = '6260100600362'
group by pro_ID order by pro_ID asc