我有一份包含开始日期和结束日期的员工清单。每次他们更换经理时,都会生成一个新行。我想弄清楚他们整个一年中每个月的部门是什么。
以下是数据:
EMP_ID startdate enddate staffgroup
494694 2012-05-24 2013-01-09 Service
494694 2013-01-09 2013-02-03 Service
494694 2013-02-03 2013-02-04 Service
494694 2013-02-04 2013-02-05 Service
494694 2013-02-05 2013-02-07 Service
494694 2013-02-07 2013-02-15 Service
494694 2013-02-15 2013-03-20 Service
494694 2013-03-20 2013-06-01 Service
494694 2013-06-01 2013-06-03 Manager
494694 2013-06-03 2013-07-01 Manager
494694 2013-07-01 2099-12-31 Manager
预期结果
EMP_ID Month staffgroup
494694 2013-01-01 Service
494694 2013-02-01 Service
494694 2013-03-01 Service
494694 2013-04-01 Service
494694 2013-05-01 Service
494694 2013-06-01 Manager
494694 2013-07-01 Manager
答案 0 :(得分:1)
创建一个包含所需月份的DATE_HELPER表:
the_date
2013-01-01
2013-02-01
...
2013-12-01
然后看起来你想要这个人在每个月开始之前拥有的最后一个人员组。
SELECT e.EMP_ID, max(e.startdate), dh.the_date
FROM DATE_HELPER dh
LEFT OUTER JOIN RAW_EMP_DATA e on (e.startdate <= dh.the_date)
GROUP BY EMP_ID, dh.the_date
Results:
EMP_ID startdate the_date
494694 2012-05-24 2013-01-01
494694 2013-01-09 2013-02-01
494694 2013-02-15 2013-03-01
494694 2013-03-20 2013-04-01
494694 2013-03-20 2013-05-01
494694 2013-06-01 2013-06-01
494694 2013-07-01 2013-07-01
494694 2013-07-01 2013-08-01
494694 2013-07-01 2013-09-01
494694 2013-07-01 2013-10-01
这将为您提供您关心的所有相关新手。所以你加入到原始表中以获得人员组:
SELECT red.EMP_ID, X.the_date as Month, red.staffgroup
FROM RAW_EMP_DATA red
INNER JOIN (
SELECT e.EMP_ID, max(e.startdate), dh.the_date
FROM DATE_HELPER dh
LEFT OUTER JOIN RAW_EMP_DATA e on (e.startdate <= dh.the_date)
GROUP BY EMP_ID, dh.the_date
) X on (X.EMP_ID = red.EMP_ID and X.startdate = red.startdate)
Results:
EMP_ID Month staffgroup
494694 2013-01-01 Service
494694 2013-02-01 Service
494694 2013-03-01 Service
494694 2013-04-01 Service
494694 2013-05-01 Service
494694 2013-06-01 Manager
494694 2013-07-01 Manager
494694 2013-08-01 Manager
494694 2013-09-01 Manager
494694 2013-10-01 Manager
答案 1 :(得分:0)
类似的东西:
SELECT EXTRACT( YEAR_MONTH FROM startdate )
FROM `employee`
将为您提供2013年10月的“201310”