title: SQL: select exact max for repeating value that based on other repeating value
body: <pre><code>Table with repeating data in each column
  |  userid   |   code   |    date    |
  |3          |  YYYYYY  | 2017-09-20 |
  |3          |  YYYYYY  | 2017-09-21 |
  |3          |  YYYYYY  | 2017-09-22 |
  |1          |  XXXXXX  | 2017-09-22 |
  |1          |  XXXXXX  | 2017-09-23 |
  |3          |  XXXXXX  | 2017-09-23 |
  |3          |  XXXXXX  | 2017-09-23 |
  |2          |  ZZZZZZ  | 2017-09-23 |
  |3          |  ZZZZZZ  | 2017-09-23 |
  |1          |  ZZZZZZ  | 2017-09-24 |
  </code></pre>
  
  <p>I need to get MAX(date) for each 'code', and get 'userid' for this MAX(date) and 'code', with group by 'code'.</p>
  
  <pre><code>SELECT
  t1.userid,
  t1.code,
  t1.date
  FROM codes AS t1
  
  INNER JOIN (
              SELECT 
                userid,
                code,
                MAX(date) as maxdate
              FROM codes
              GROUP BY code
              ) AS t2
  ON (t1.code = t2.code AND t1.date = t2.maxdate)
  ORDER BY date
  </code></pre>
  
  <p>But, MAX(date) value should be based on userid.</p>
  
  <p>If code has user 1 and 2 and 3 then max date should be based on user 3 codes.</p>
  
  <p>If code has user 2 and 3 then max date should be based on user 3 codes.</p>
  
  <p>If code has user 1 and 2 then max date should be based on user 2 codes.</p>
  
  <p>If code has user 3 then max date should be based on user 3 codes.</p>
  
  <p>If code has user 2 then max date should be based on user 2 codes.</p>
  
  <p>If code has user 1 then max date should be based on user 1 codes.</p>
  
  <p>Response shuld contain: code, userid, and MAX(date) based on 'userid' value with gpoup by 'code' (one row for each code)</p>
  
  <p>How to add this select?
  Thanks for any help)
  <a href="http://sqlfiddle.com/#!9/ccb50/1/0" rel="nofollow noreferrer">SQL Fiddle</a></p>