我有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
我需要得到
余额是收支之差。
结构:
按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
答案 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