从Mysql中的多个组获取最新条目

时间:2015-12-17 10:44:48

标签: mysql

如果问题标题不清楚,请道歉。不知道如何在一行中说出以下内容。

我希望我能够解释我想要实现的目标。这让我头疼。

目前,我有一张表,记录了不同项目员工的培训状况。结构是这样的:

--------------------------------------------------------------
|id|timestamp           |employee  |project    |status       |
--------------------------------------------------------------
|1 |2015-10-01 00:00:00 | john doe | project_1 | In Training |
|2 |2015-10-04 00:00:00 | jane doe | project_1 | In Training |
|3 |2015-11-01 00:00:00 | john doe | project_1 | Live        |
|4 |2015-10-08 00:00:00 | john doe | project_2 | In Training |
|5 |2015-11-01 00:00:00 | jane doe | project_2 | In Training |
|6 |2015-11-09 00:00:00 | jane doe | project_3 | Live        |

现在,管理层要求提供一个表/视图,其中概述了每位员工的最新状态。所以我正在寻找一个返回这个的查询:

-----------------------------------------------------
| employee | project_1   | project_2   | project_3   |
-----------------------------------------------------
| John Doe | Live        | In Training |             |
| Jane Doe | In Training | In Training | Live        |

因此,查询应查找每个员工和项目的最新条目,并返回该项目的状态。

这有可能吗?

1 个答案:

答案 0 :(得分:0)

好吧,你将2个问题混为1个。第一个问题是如何获得每个项目每个员工的最新状态。第二个是如何在列中显示数据。第一个问题更有趣,所以这就是我要回答的问题。

SELECT DISTINCT x.employee
              , y.project
              , z.timestamp
              , z.status 
           FROM my_table x 
           JOIN my_table y 
           LEFT 
           JOIN 
              ( SELECT a.* 
                  FROM my_table a 
                  JOIN 
                     ( SELECT employee 
                            , project
                            , MAX(timestamp) max_timestamp 
                         FROM my_table 
                        GROUP 
                           BY employee
                            , project
                     ) b 
                    ON b.employee = a.employee 
                   AND b.project = a.project 
                   AND b.max_timestamp = a.timestamp
              ) z 
             ON z.employee = x.employee 
            AND z.project = y.project;