我正在研究费用/预算跟踪系统,并且陷入了某些困境。
我有4张桌子
tblProjects
tblCategory
tblExpenses
tbl收入
tblProject与1:1的tblCategory相关,
tblExpenses与1:1的tblProject有关,
tbl收入与1:1的tblProjects有关
我正在尝试按年份(从tblProjects.proj_sdate
列中获得每个类别组的费用和收入之和),以及一列显示损益(费用-收入)。
例如,我想知道什么是总支出,总收入,旅行,体育等方面的损益的价值?
下面是我想要实现的示例;
我尝试使用以下查询,但返回的数据错误:
SELECT category.cat_title as Category,date_format(projects.proj_sdate, '%Y')
as Year, (select sum(incomes.inc_amount) from incomes where
incomes.projects_id = projects.proj_id) as Total_Income,
(select sum(expenses.exp_amount) from expenses where expenses.projects_id =
projects.proj_id) as Total_Expenses,
(select ifnull(sum(incomes.inc_amount),0) from incomes where
incomes.projects_id = projects.proj_id) - (select
ifnull(sum(expenses.exp_amount),0) from expenses where expenses.projects_id
= projects.proj_id) as PnL from category inner join projects on
projects.proj_cat = category.cat_id group by category.cat_id
答案 0 :(得分:1)
您可以在下面尝试-
SELECT category.cat_title as Category,Proj_title,
date_format(projects.proj_sdate, '%Y') as Year,
sum(expenses.exp_amount) as total_income
coalesce(sum(incomes.inc_amount),0) - sum(expenses.exp_amount) as pnl
from
category inner join projects on projects.proj_cat = category.cat_id
inner join expenses on expenses.projects_id = projects.proj_id
inner join incomes on incomes.projects_id = projects.proj_id
group by category.cat_title,Proj_title,date_format(projects.proj_sdate, '%Y')