您好,我有2张表的员工和通过员工ID关联的病假,基本上我想创建一个结果集,其中有一个列按月和年过滤,而另一列仅按年过滤
EMPLOYEES MEDICAL
|employee|ID| |ID|DateOfLeave|
A 1 1 2019/1/3
B 2 1 2019/4/15
C 3 2 2019/5/16
D 4
select employees.employee,Employees.ID,count(medical.dateofleave) as
NumberofLeaves
from employees
left outer join Medical on employees.emp = MedBillInfo.emp
and month(medbillinfo.date) in(1) and year(medbillinfo.date) in (2019)
group by Employees.employee,employees.ID
RESULT SET
|Employee|ID|NumberOfLeaves|YearlyLeaves|--i want to join this column
A 1 1 2
B 2 0 1
C 3 0 0
D 4 0 0
但是我不知道如何在当前sql语句中编写将年叶子列添加到当前结果集的方法,该结果集仅是employee,id和numberofleaves
答案 0 :(得分:0)
您的问题可能需要更正,因为按条件分组与选择列不匹配。但是根据您的要求,我认为您需要使用截断日期功能才能按年对叶子进行分组。对于SQL Server,有YEAR(date)函数可返回给定日期的年份。在您的情况下,该日期将是MEDICAL.DateOfLeave。
答案 1 :(得分:0)
我认为您需要条件聚合:
select e.employee, e.ID,
count(*) as num_leaves,
sum(case when month(m.date) = 1 then 1 else 0 end) as num_leaves_in_month_1
from employees e left join
Medical m
on e.emp = m.emp
where m.date >= '2019-01-01' and m.date < '2020-01-01'
group by e.employee, e.ID;
注意:
where
子句,该子句似乎是指不存在的表别名。