SQL:如何按最大日期分组

时间:2015-09-30 14:32:23

标签: mysql

我对SQL很陌生,所以请原谅应该是什么样的基本查询。我一直在寻找和尝试转换其他类似的答案代码以使我的工作正常,但我似乎无法做到正确。

我有2张桌子。这些表通过唯一的员工ID(EMPLID)进行链接。表1(JOB)包含各种与工作相关的信息,如标题和表2(TITLE_CHANGES),包括促销活动,原因和日期。我需要根据最近的TITLE_CHANGES日期开发一个从JOB和TITLE_CHANGES表返回*的查询。

仅供参考,这不反映我的实际表格数据。我过于简单化了,以便更容易解释。

It should return:

EMLPID |     TITLE    |TitleDate   |TitleChnageReason|Requested_Date

12345  |  Specialist 2| 02/01/2015|      Merit       |01/31/2015

JOB table    
  EMPLID    |         Title       | Title Date  
---------+---------------+----------------+  
 12345      |  Specialist 2       | 02/01/2015       
--------+----------------+----------------  
 12345      |  Specialist 1       | 09/01/2014  
--------+----------------+----------------  
 44576      |  Analyst 3          | 05/01/2015  
--------+----------------+----------------  
 44576      |  Analyst 2          | 03/01/2014  
--------+---------------------+-----------  

TITLE_CHANGES Table

  EMPLID    | Title change reason | Requested_Date  
------------+---------------------+----------------+  
 12345      |  Merit              | 01/31/2015  
------------+---------------------+----------------  
 12345      |  Newhire            | 08/30/2014  
------------+---------------------+----------------  
 44576      |  Promotion          | 04/30/2015  
------------+---------------------+----------------  
 44576      |  Newhire            | 02/28/2014  
------------+---------------------+----------------  

感谢您的帮助!

克雷格

5 个答案:

答案 0 :(得分:0)

尝试此查询

SELECT j.EMPLID, 
SUBSTRING_INDEX(GROUP_CONCAT(j.TITLE ORDER BY j.TitleDate DESC),',',1) AS title,
SUBSTRING_INDEX(GROUP_CONCAT(j.TitleDate ORDER BY j.TitleDate DESC),',',1) AS title_date, 
SUBSTRING_INDEX(GROUP_CONCAT(tc.TitleChnageReason ORDER BY tc.Requested_Date DESC),',',1) AS title_change_reson,
SUBSTRING_INDEX(GROUP_CONCAT(tc.Requested_Date ORDER BY tc.Requested_Date DESC),',',1) AS request_date,
FROM JOB j
JOIN TITLE_CHANGES tc ON(tc.EMPLID = j.EMPLID)
GROUP BY j.EMPLID

答案 1 :(得分:0)

试试这个

SELECT j.emplid AS 'EMPLID', j.title AS 'TITLE', j.title_date AS 'TitleDate', e.reason AS 'TitleChangeReason', q.requested_date AS 'Requested_Date'
FROM
    job j
    INNER JOIN
    (SELECT a.* 
        FROM title_changes a
        INNER JOIN (SELECT emplid, MAX(requested_date) as rd FROM title_changes GROUP BY 1) b 
        ON a.emplid=b.emplid AND a.requested_date=b.rd) 
    e ON j.emplid=e.emplid

答案 2 :(得分:0)

选择* 来自工作j 内连接Title_Change tj 在j.empid = tj.empid上 由j.titledate desc命令

答案 3 :(得分:0)

选择Top(1)j.empid,j.title,j.titleDate,tj.TitleChangeReason,tj.Request_Date 来自工作j 内连接Title_Change tj 在j.empId = tj.empid上 由j.TitleDate desc命令

试试这个, 感谢。

答案 4 :(得分:-1)

从JOB j,TITLE_CHANGES tc中选择j.EMPLID,j.Title,j。标题日期,标题更改原因,MAX(tc.Requested_Date),其中j.EMPLID = tc.EMPLID