完成MAX()但使用来自更多表的数据

时间:2014-01-07 20:00:11

标签: mysql sql max

好吧我最终在一张桌子上使用max()正确拉出max() - 花了一些时间来了解发生了什么并在使用它时读取了mysql的限制

我花了一些时间在sqlfiddle上做一些演示数据(下面一个只有一个表上的最大值

http://sqlfiddle.com/#!2/fff224/1

我想要的东西(以及我在过去2小时内尝试使用此功能的吸收)是如何合并另一个不需要使用max的表格(我已将它们包含在sqlfiddle中

我将追随的结果将是

case_number full_address    case owner  client  compiled date(max())    recommendation
1000      1 high street       bob     london        14/12/2012                   let
1001      2 high street       ken     Compton       13/12/2013                   sell
1002      3 high street      ken      Leeds        14/12/2013                    sell

完成从客户端\ staff \到案例流程之间的内部联接我只是这个嵌套的选择最大值我会摔倒

1 个答案:

答案 0 :(得分:1)

SELECT p.case_number
     , p.full_address
     , s.case_owner_name 'case owner'
     , c.client_name client
     , r.compiled_date
     , r.recommendation
  FROM case_process p
  JOIN staff s
    ON s.case_owner_number = p.case_owner_number
  JOIN client c
    ON c.client_number = p.client_number
  JOIN reporting r
    ON r.case_number = p.case_number
  JOIN (SELECT case_number,MAX(compiled_date) max_compiled_date FROM reporting GROUP BY case_number) x
    ON x.case_number = r.case_number
   AND x.max_compiled_date = r.compiled_date;

 +-------------+---------------+------------+---------+---------------+----------------+
 | case_number | full_address  | case owner | client  | compiled_date | recommendation |
 +-------------+---------------+------------+---------+---------------+----------------+
 |        1000 | 1 high street | Bob        | London  | 2012-12-14    | let            |
 |        1001 | 2 high street | Ken        | Compton | 2013-12-13    | sell           |
 |        1002 | 3 high street | Ken        | Leeds   | 2012-12-14    | sell           |
 +-------------+---------------+------------+---------+---------------+----------------+
 3 rows in set (0.00 sec)

 fiddle of same... http://sqlfiddle.com/#!2/fff224/7