【问题标题】:SQL query for getting conversion days between Active to inactive of employee用于获取员工活跃到非活跃之间转换天数的 SQL 查询
【发布时间】:2017-03-14 07:50:24
【问题描述】:

ID EmployeeID 状态 EffectiveDate


 1       110545        Active        01-01-2011
 2       110700        Active        05-01-2012
 3       110060        Active        05-01-2012
 4       110222        Active        30-06-2012
 5       110222        Resigned      22-05-2016
 6       110545        Resigned      01-07-2012
 7       110545        Active        12-02-2013

如何使用 T-SQL 查找每个员工的状态为“活动”和“非活动”之间经过的时间量,不包括重新加入员工的当前状态为“活动”。

输出应该

ID     EmployeeID      Days

 1       110222     1422
 2       110545      371

【问题讨论】:

  • 使用 DateDiff(),这可能会有所帮助:stackoverflow.com/a/9521452/1830909
  • 我没有得到你想要的,你能给出预期的结果并解释一下吗?
  • 对于 Emp 110545 ,我需要从活动到非活动的天数转换 w.r.t 当前状态.. 所以对于 emp 110545 应该是 01-01-2011 (ActiveDate) 到 01-07-2012(辞职日期)
  • 你知道从活跃到不活跃的天数转换到当前状态的天数是什么意思,但我不知道。
  • 查看参考链接以了解如何提出完美问题:spaghettidba.com/2015/04/24/…

标签: sql sql-server-2012


【解决方案1】:

一种方法是搜索所有Resigned 状态,然后使用cross apply 查找之前的Active 状态,如下所示:

declare @Emp table (ID int, EmployeeID int, Status varchar(8), EffectiveDate date)
insert into @Emp (ID, EmployeeID, Status, EffectiveDate) values
(1, 110545, 'Active', '2011-01-01'),
(2, 110700, 'Active', '2012-01-05'),
(3, 110060, 'Active', '2012-01-05'),
(4, 110222, 'Active', '2012-06-30'),
(5, 110222, 'Resigned', '2016-05-22'),
(6, 110545, 'Resigned', '2012-07-01'),
(7, 110545, 'Active', '2013-02-12')


select
    row_number() over (order by EmployeeID) as ID,
    e.EmployeeID,
    datediff(dd, e2.EffectiveDate, e.EffectiveDate) as Days
from @Emp as e
cross apply
(
    select top 1 e2.EffectiveDate
    from @Emp as e2
    where e.EmployeeID = e2.EmployeeID and e2.EffectiveDate < e.EffectiveDate
    order by EffectiveDate desc
) as e2
where e.Status = 'Resigned'

结果

ID     EmployeeID      Days
 1       110222       1422
 2       110545        547*

*您的样本EffectiveDate 数据格式为DD-MM-YYYY

【讨论】:

  • 创建表后,当我运行 select 查询语句时,它显示错误消息:消息 208,级别 16,状态 1,行 1 无效对象名称“EMployeeID”。
【解决方案2】:

试试这个

 select *, DATEDIFF(day, date, todate) as totalday from 
(select e.employeeid,e.status,e.date,MIN(em.date) as todate from tbl_emp e
left join tbl_emp em on e.date < em.date and e.employeeid = em.employeeid
where e.status = 'active'
group by e.employeeid,e.status,e.date
having MIN(em.date) is not null 
)
as m
order by date

【讨论】:

  • 感谢 simarjeet 它有很大帮助,但我修改了我的问题 w.r.t 输出,请查看它。
  • Simarjeet,预期输出应为:- ID EmployeeID Days 1 110222 1422 2 110545 547*
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多