写了这么长时间sql 也是第一次遇到所以做成笔记与大家一起分享
先整理一下需求:
1.部门按照要求将部门的所有费用进行统计 每种费用要填写额度(例如:公务:1000元,工资:6000等)填写具体数据之后提交一条记录做审核用,可以有多条审核通过,依照最新一条审核通过的费用详情做处理。
- 要求按照固定部门单个月(例如A部门6月份的数据)查找数据的时候 按照部门审核通过的时间最大
3.可以按照部门类型查找(例如 部门a 部门b 同属于一种类型部门)那可以在查找时候将相同类型的费用数据合并
4.可以按照年度查找(包括单个部门、同种类型部门 )全年的费用详情
首先说一下表结构

这里主要用到的字段有 propose_time_year,approve_time, status,departmentId四个字段
select
baebda.cost_id cost_id,
baebda.cost_set_name,
baebda.cost_type,
baebda.system_con_expenditure,
sum(baebda.adjust_budget) adjust_budget
from ( select
asd.id ,asd.department_id
from (select a.id,a.approve_time,a.department_id,a.adjust_month from budget_annual_expense_budget_adjust a
inner join department so on a.department_id = so.id
where a.`status` =3 //审核通过状态是3
and a.propose_time_year = #{year} //年份是2019
and a.adjust_month < #{month} //<为mybatis中的小于号
<if test="orgType != null">
and so.org_type = #{orgType}
</if>
<if test="orgId != null">
and a.department_id = #{orgId} //传类型 和部门 两个不能一起传(一起传可以没比要 部门id唯一)
</if>
ORDER BY a.approve_time desc
) asd
group by asd.department_id,asd.adjust_month
ORDER BY asd.approve_time desc
) baeba
inner join budget_annual_expense_budget_detail_adjust baebda on baeba.id = baebda.annual_expense_budget_adjust_id
group by baebda.cost_id
网友评论