2

我有一个包含开始日期和结束日期的员工名单。每次他们更换经理时,都会生成一个新行。我试图弄清楚他们全年每个月的部门是什么。

这是数据:

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
4

2 回答 2

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
于 2013-11-01T23:24:14.397 回答
0

就像是:

SELECT EXTRACT( YEAR_MONTH FROM startdate ) 

FROM  `employee` 

将为您提供 2013 年 10 月的“201310”

于 2013-10-12T23:44:24.477 回答