Mysql 如何获取产品名称、数量和余额?

Mysql 如何获取产品名称、数量和余额?,mysql,sql,database,Mysql,Sql,Database,我有三张桌子 DMZ: Ndm int - number of Document Ddm date - date of supply Pr int - 1(income), 2(expense) 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

我有三张桌子

DMZ:

Ndm int - number of Document
Ddm date - date of supply
Pr int - 1(income), 2(expense)
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
Ktov - id if product
Ntov - name of product
DMS:

Ndm int - number of Document
Ddm date - date of supply
Pr int - 1(income), 2(expense)
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
Ktov - id if product
Ntov - name of product
TOV:

Ndm int - number of Document
Ddm date - date of supply
Pr int - 1(income), 2(expense)
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
Ktov - id if product
Ntov - name of product
我需要得到 余额是收入和支出之间的差额。

结构:

  • 产品名称(Ntov)
  • 残留量
  • 余额的金额精确到分(差额 在销售过程中花费的和收到的之间)
  • 按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数据:
    DMZ数据:
    TOV数据:

    结果:

    您可以聚合和执行条件和。考虑:

    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
    

    示例数据和期望的结果将是一个很大的帮助,特别是因为列名不是很有意义。抱歉,添加了带有数据的屏幕截图谢谢,我不知道我可以使用2次“when”