如何获得名称,产品数量和余额?

时间:2019-12-15 13:55:23

标签: mysql sql database

我有3张桌子

DMZ:

Ndm int - number of Document
Ddm date - date of supply
Pr int - 1(income), 2(expense)

DMS:

Id int
Kol decimal - quantity of product
Price decimal
Ndm int - number of document foreign key with DMZ
Ktov int - id of product foreign key with TOV

TOV:

Ktov - id if product
Ntov - name of product

我需要得到 余额是收支之差。

结构:

  1. 产品名称(Ntov)
  2. 残留量
  3. 余额精确到美分(差额 花费与销售过程中收到的收益之间的关系

按Ntov排序, 对于每种产品, 对于每种有收入甚至有支出的产品,报告中的一个摘要行

现在我有这个sql请求,但是我被卡住了:/ 请帮助我,我做错了什么?

SELECT
 Ntov AS Product,
 SUM(CASE WHEN Pr = 1 then Kol*Price ELSE 0 END) AS Income,
 SUM(CASE WHEN Pr = 2 then Kol*Price ELSE 0 END) AS Expense,
 COUNT(DMS.Kol) AS LeftProducts
FROM DMS LEFT JOIN TOV
on DMS.Ktov = Tov.Ktov 
LEFT JOIN DMZ on DMS.Ndm = DMZ.Ndm
GROUP BY Ntov, Kol, Price
ORDER BY Product

DMS数据:http://prntscr.com/qb3qiq
DMZ的数据:http://prntscr.com/qb3qog
TOV数据:http://prntscr.com/qb3qrl
结果:http://prntscr.com/qb3q92

1 个答案:

答案 0 :(得分:1)

您可以汇总并进行条件求和。考虑:

select
    t.ntov,
    sum(case z.pr when 1 then s.kol when 2 then - s.kol else 0 end) residue,
    sum(case z.pr when 1 then s.price when 2 then - s.price else 0 end) balance
from tov t
left join dms s on t.ktov = s.ktov
left join dmz z on s.ndm = z.ndm
group by t.ntov, t.ktov
order by t.ntov