从由2个已连接表

时间:2017-09-19 18:55:34

标签: mysql greatest-n-per-group

我有一个复杂的问题,我对MYSQL不太满意。我希望有人可以帮助我 我有2张桌子。这些表格的片段:

  1. Members_per_year
  2. ID | Member_ID | Business_year_ID | AS_ID
    1 ........... 1 ............................ 56 ........ ........... 12个
    10004 ... 1 ............................ 55 ................ ... 12个
    10005 ... 1 ............................ 54 ................ ... 11个
    10002 ... 1 ............................ 57 ................ ... 30个
    2 ........... 2 ............................ 58 ........ ........... 40个
    3 ........... 3 ............................ 58 ........ ........... 27

    1. ID | Business_year
      54 ...... 2012-2013
      55 ...... 2013-2014
      56 ...... 2014-2015
      57 ...... 2015-2016
      58 ...... 2016-2017

      我要做的是将这两个表合并到Members_per_year上。 Business_year_ID和Year.ID列。之后,我想按Member_ID对数据进行分组,因此每个成员返回1行。问题是它应该是该成员具有最大Business_year的数据。我设法将一个查询放在一起,但它无法正常工作。查询是:

      SELECT Member_ID, Business_year_ID, MAX(Year.Business_year), Year.ID AS YearID, AS_ID  
      FROM Members_per_year  
      INNER JOIN Year ON Members_per_year.Business_year_ID = Year.ID  
      GROUP BY Member_ID
      

      它返回:

      Member_ID | Business_year_ID | MAX(Year.Business_year)| YearID | AS_ID
      1 ........................... 56 ..................... .......... 2015 - 2016年56 .................... 12个..........
      2 ........................... 58 ..................... 2016 - 2017年.......... 58 .................... 40个..........
      3 ........................... 58 ..................... .......... 2016-2017 .................... 58 .......... 27

      它返回正确的最大Business_year,但关联的Business_year_ID和YearID不正确。基本上,它选择Business_year_ID的第一个值和Business_year的MAX。不是与MAX(Business_year)对应的Business_year_ID。有没有人知道为什么会这样,以及如何解决它?

      修改
      我故意搜索Business_year而不是Business_year_ID。这是一个预防性问题,以防较高的ID与实际较高的业务年度不相等。

1 个答案:

答案 0 :(得分:0)

您需要一个子查询来获取每个成员的最大年份,然后将结果与原始表一起加入:

select b.*, c.*
from (
  select Member_ID, max(Business_year_ID) y
  from Members_per_year
  group by Member_ID) a
join Members_per_year b on a.Member_ID = b.Member_ID and a.y = b.Business_year_ID
join Year c on b.Business_year_ID = c.ID;