Mysql 如何获取产品名称、数量和余额?
我有三张桌子 DMZ: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
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
我需要得到
余额是收入和支出之间的差额。结构:
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”