总结所有以前的工作经验(以月为单位),其中行是动态的(1 行代表 1 次经验)并且每个员工都不同

Sum all the previous work experiences (into months) where rows are dynamic (1 row for 1 experience) and different for each employee

我有一个 table 存储员工的工作经验历史,其中每个经验都存储为 1 行。

TblWorkExp :

--------------------------------------------------
ID      | ExperienceID |  From_Date | To_Date    |
--------------------------------------------------
EMP001  |      1       |  1-Jan-18  | 31-Dec-18  |
--------------------------------------------------
EMP001  |      2       |  1-Jan-19  | 31-May-19  |
--------------------------------------------------
EMP001  |      3       |  1-Jun-19  | 31-Dec-19  |
--------------------------------------------------
EMP002  |      1       |  1-Jan-19  | 28-Feb-19  |
--------------------------------------------------
EMP002  |      2       |  1-Apr-19  | 31-May-19  |
--------------------------------------------------

我的输出应该是

---------------------------
ID      | Total Experience|  
---------------------------
EMP001  |      24 Months  |  
---------------------------
EMP002  |      04 Months  | 
---------------------------

我最初所做的是计算
之间的 datediff 月数 Min(ExperienceID) from_date 和 max(ExperienceID) to_date 如果 jobs

之间没有差距,这会给我结果
Select ExpMin.ID, datediff(month,ExpMin.From_date ,ExpMax.To_Date) as 'Total Experience'
 from TblWorkExp ExpMin, TblWorkExp ExpMax 
where 
ExpMin.ID = ExpMax.ID and
ExpMin.From_date = (select min(a.From_date) from TblWorkExp a where ExpMin.ID = a.ID )and
ExpMax.To_date = (select Max(a.To_date) from TblWorkExp a where ExpMax.ID = a.ID )

当作业之间没有间隙时,它工作正常。我需要像

这样的结果
---------------------------
ID      | Total Experience|  
---------------------------
EMP001  |      24 Months  |  
---------------------------
EMP002  |      04 Months  | 
---------------------------

这是您的问题。

select ID, sum(datediff(month, from_date, to_date)) As [Total Experience] from TblWorkExp 
group by ID