我想在两行不同的表之间减去:
我创建了一个名为view
的{{1}}和名为leave_taken
的{{1}}。
我想从这两个表中得到这个结果:
table
并按leave_balance
分组
两个表的代码
-----------------查看Leave_Taken -----------
leave_taken.COUNT(*) - leave_balance.balance
----------------表leave_balance ----------
leave_type_id_leave_type
-------表格离开----------
CREATE ALGORITHM = UNDEFINED DEFINER=`1`@`localhost` SQL SECURITY DEFINER
VIEW `leave_taken`
AS
select
`leave`.`staff_leave_application_staff_id_staff` AS `staff_leave_application_staff_id_staff`,
`leave`.`leave_type_id_leave_type` AS `leave_type_id_leave_type`,
count(0) AS `COUNT(*)`
from
(
`leave`
join `staff` on((`staff`.`id_staff` = `leave`.`staff_leave_application_staff_id_staff`))
)
where (`leave`.`active` = 1)
group by `leave`.`leave_type_id_leave_type`;
答案 0 :(得分:1)
好吧,我仍然认为你没有提供足够的信息。获得一些样本数据和预期输出(以表格格式)会非常有用非常有用。也就是说,我可能会有一些你可以开始合作的东西。此查询查找所有工作人员,计算其当前休假(按类型分组),并通过休假类型确定该休假与其余额之间的差异。看看它,更重要的是(也许)我使用的sqlfiddle here中包含样本数据(对于确定这是否是数据的正确路径非常重要)。
SELECT
staff.id_staff,
staff.name,
COUNT(`leave`.id_leave) AS leave_count,
leave_balance.balance,
(COUNT(`leave`.id_leave) - leave_balance.balance) AS leave_difference,
`leave`.leave_type_id_leave_type AS leave_type
FROM
staff
JOIN `leave` ON staff.id_staff = `leave`.staff_leave_application_staff_id_staff
JOIN leave_balance ON
(
staff.id_staff = leave_balance.staff_id_staff
AND `leave`.leave_type_id_leave_type = leave_balance.leave_type_id_leave_type
)
WHERE
`leave`.active = 1
GROUP BY
staff.id_staff, leave_type;
祝你好运!