确定。这有点复杂。我一直在努力实现它,到目前为止还没有。
我有三张桌子。 leave_approval leave_applications ml_leave_type
这是leave_approval表
然后从leave_application_id链接到leave_application
现在出现了棘手的问题, 我想从表中获得两条记录。
- 我想要员工在2014年的总休假
- 我想要员工在2014年11月份采取的总叶子数
醇>
所以意味着需要每年和每月两个不同方法的两列。
到目前为止我有查询。
SELECT
LA.employee_id,
DATEDIFF(
LA.approved_to,
LA.approved_from
) AS TotalLeavesTaken,
LAPP.`entitlement_id`,
LAPP.`ml_leave_type_id`,
LA.leave_application_id,
LA.approved_from AS LeaveFrom,
LA.approved_to AS LeaveTo
FROM
leave_approval LA
INNER JOIN leave_application LAPP
ON LAPP.application_id = LA.leave_application_id
WHERE YEAR(LA.approval_date) = 2014
AND LA.`employee_id` = 1
这是我得到的查询结果..
= - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = -
更新
我可能无法清楚地解释我的问题。
我想要实现的是添加两个额外的列而不删除我的列。我的意思是我使用大多数/我所有的选择字段
另外,我希望2014年的总叶数在一个栏目中,而在一年中不同领域的总叶数将为该年份。
所以这里是我想要的一个例子。>
ml_leave_type_id | Total Leaves Taken in Year (e-g 2014) | Total Leaves taken in Month (e-g November)
1 10 2
2 6 0
3 4 1
答案 0 :(得分:0)
Edit2:澄清要求后更新的select语句。更新包括使用JOIN而不是UNION ALL重新组织
select a.*, b.*
from (
SELECT
LA.employee_id,
DATEDIFF(
LA.approved_to,
LA.approved_from
) AS TotalLeavesTaken,
LAPP.`entitlement_id`,
LAPP.`ml_leave_type_id`,
LA.leave_application_id,
LA.approved_from AS LeaveFrom,
LA.approved_to AS LeaveTo
FROM
leave_approval LA
INNER JOIN leave_application LAPP
ON LAPP.application_id = LA.leave_application_id
WHERE YEAR(LA.approval_date) = 2014
AND LA.`employee_id` = 1
) a
JOIN (
SELECT
LA.employee_id,
DATEDIFF(
LA.approved_to,
LA.approved_from
) AS TotalLeavesTaken,
LAPP.`entitlement_id`,
LAPP.`ml_leave_type_id`,
LA.leave_application_id,
LA.approved_from AS LeaveFrom,
LA.approved_to AS LeaveTo
FROM
leave_approval LA
INNER JOIN leave_application LAPP
ON LAPP.application_id = LA.leave_application_id
WHERE MONTHNAME(LA.approval_date) = 'November'
AND LA.`employee_id` = 1
) b
ON a.employee_id = b.employee_id
答案 1 :(得分:0)
会这样吗?
employee_id = 1,2014年的总叶数
SELECT
LA.employee_id,
SUM(
DATEDIFF(
LA.approved_to,
LA.approved_from
)
) AS TotalLeavesTaken,
LAPP.`entitlement_id`,
LAPP.`ml_leave_type_id`,
LA.leave_application_id,
LA.approved_from AS LeaveFrom,
LA.approved_to AS LeaveTo
FROM
leave_approval LA
INNER JOIN leave_application LAPP
ON LAPP.application_id = LA.leave_application_id
WHERE YEAR(LA.approval_date) = 2014
AND LA.`employee_id` = 1
GROUP BY LA.`employee_id` = 1
employee_id的总休假= 1,年= 2014年和月= 11
SELECT
LA.employee_id,
SUM(
DATEDIFF(
LA.approved_to,
LA.approved_from
)
) AS TotalLeavesTaken,
LAPP.`entitlement_id`,
LAPP.`ml_leave_type_id`,
LA.leave_application_id,
LA.approved_from AS LeaveFrom,
LA.approved_to AS LeaveTo
FROM
leave_approval LA
INNER JOIN leave_application LAPP
ON LAPP.application_id = LA.leave_application_id
WHERE YEAR(LA.approval_date) = 2014
AND MONTH(LA.approval_date) = 11
AND LA.`employee_id` = 1
GROUP BY LA.`employee_id` = 1
我确实注意到你的数据集中有些日期过于紧张。例如:
employee_id = 1正在休假2014/11/01 - 2014/11/06和2014/11/05 - 2014/11/08。什么是2014/11/05和2014/11/06日期的交易。系统将如何处理这种情况