title: How to get id of the row which was selected by aggregate function?
body: <p>I have next data:</p>
  
  <pre><code>id | name | amount | datefrom
  ---------------------------
  3  | a    |  8     | 2018-01-01
  4  | a    |  3     | 2018-01-15 10:00
  5  | b    |  1     | 2018-02-20
  </code></pre>
  
  <p>I can group result with the next query:</p>
  
  <pre><code>select name, max(amount) from table group by name
  </code></pre>
  
  <p>But I need the <code>id</code> of selected row too. Thus I have tried:</p>
  
  <pre><code>select max(id), name, max(amount) from table group by name
  </code></pre>
  
  <p>And as it was expected it returns:</p>
  
  <pre><code>id | name | amount
  -----------
  4  | a    |  8
  5  | b    |  1
  </code></pre>
  
  <p><strong>But I need the id to have <code>3</code> for the amount of <code>8</code>:</strong></p>
  
  <pre><code>id | name | amount
  -----------
  3  | a    |  8
  5  | b    |  1
  </code></pre>
  
  <p>Is this possible?</p>
  
  <p>PS. This is required for billing task. At some day <code>2018-01-15</code> configuration of <code>a</code> was changed and user consumes some resource 10h with the amount of <code>8</code> and rests the day 14h -- <code>3</code>. I need to count such a day by the maximum value. Thus row with <code>id = 4</code> is just ignored for 2018-01-15 day. (for next day 2018-01-16 I will bill the amount of <code>3</code>)<br>
  So I take for billing the row:</p>
  
  <pre><code>3  | a    |  8     | 2018-01-01
  </code></pre>
  
  <p>And if something is wrong with it. I must report that row with <code>id == 3</code> is wrong.</p>
  
  <p>But when I used aggregation function the information about <code>id</code> is lost.</p>
  
  <p>Would be awesome if this is possible:</p>
  
  <pre><code>select current(id), name, max(amount) from table group by name
  select aggregated_row(id), name, max(amount) from table group by name
  </code></pre>
  
  <p>Here <code>agg_row</code> refer to the row which was selected by aggregation function <code>max</code></p>
  
  <p><strong>UPD</strong><br>
  I resolve the task as:</p>
  
  <pre><code>SELECT 
      (
         SELECT id FROM t2 
         WHERE id = ANY ( ARRAY_AGG( tf.id ) ) AND amount = MAX( tf.amount ) 
      ) id,
      name, 
      MAX(amount) ma,
      SUM( ratio )
  FROM t2  tf
  GROUP BY name
  </code></pre>
  
  <p><strong>UPD</strong><br>
  It would be much better to use <a href="https://stackoverflow.com/a/52556512/4632019">window functions</a></p>