我的数据库中有四个表,如下所示:
Transactions
用于区分购买和销售交易Products
中维护产品详细信息Stocks
用于维护产品数量BillDetails
用于维护Purchase
和Sales
我确实尝试过使用界面进行买卖操作,并且它可以正常工作 但是我在使用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
由于我只售出上述产品之一,但我的查询却给我错误的销售和购买结果,如以下屏幕截图所示。
基于表信息,正确的信息或结果应类似于以下内容。
答案 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