title: Postgres join and distinct query
body: <p>I have two tabels</p>
  
  <pre><code>   user
      id |  name   
      -------------
      1  |  User1 | 
      2  |  User2 |
      3  |  User3 |
      4  |  User4 |
  </code></pre>
  
  <p>User can change name in any moment.
  And another tabel </p>
  
  <pre><code>   order
      id |user_name | user_id | price | order_date  
      ---------------------------------------------
      1  |  OldUser3| 3       |  5    | 2017-07-12 08:01:00.000000
      2  |  NewUser3| 3       |  6    | 2017-07-12 09:01:00.000000
      3  |  User1   | 1       |  8    | 2017-07-12 10:01:00.000000
      4  |  NewUser |         |  10   | 2017-07-12 11:01:00.000000
      5  |  NewUser |         |  100  | 2017-07-12 12:01:00.000000
  </code></pre>
  
  <p>user_name copied from tabel user in moment making order and if user change name several times there are can be diferent value. </p>
  
  <p>user_id can be null if it's not registered user</p>
  
  <p>I need result tabel like this</p>
  
  <pre><code> order
      no |user_name | user_id | total_pr| count |  last_order
      ---------------------------------------------
      1  |  NewUser3| 3       |  11     |   2   |2017-07-12 09:01:00.000000
      2  |  User1   | 1       |  8      |   1   |2017-07-12 10:01:00.000000
      3  |  NewUser |         |  10     |   1   |2017-07-12 11:01:00.000000
      4  |  NewUser |         |  100    |   1   |2017-07-12 12:01:00.000000
  </code></pre>
  
  <p>user_name value must take from bigest order_date and need to sort by any column
  and if user_id is null that all user with the same name it's different users</p>
  
  <p>I try this </p>
  
  <pre><code>SELECT  order.user_id, order.user_name, SUM(price), COUNT(order.user_id), MAX(order_date) 
  FROM order, user
  WHERE  
        order.order_date  &gt;= '2017-07-01 08:01:00.000000'
        AND order.order_date  &lt;= '2017-07-15 08:01:00.000000'
  GROUP BY user_id, user_name ORDER BY count ASC
  </code></pre>
  
  <p>but its not all</p>