How to get the latest 2 rows ( PostgreSQL )
<p>I need your help to modify a query to accomplish the requirement.</p>

<p>According to the GATHER_TIME, I want to show the VALUE of the NAMEs.
The query runs every 1 minute, and it should get 2 rows all the time. 
In case, there is no data at that time, it should get the past( 1 minute earlier ) data for the Name.</p>

<p>Here, specific requirement is that I should not consider seconds value in Timestamp value(GATHER_TIME).  </p>

<p>I tried to make a query like below.
It only gets the latest data.</p>

<p>Can you help me out?</p>

<h1>Query</h1>

<pre><code>select NAME,sum(VALUE)
FROM TestTable
WHERE substring(to_char(gather_time,'YYYY-MM-DD HH24:MI:SS'),1,16) IN ( SELECT MAX(substring(to_char(gather_time,'YYYY-MM-DD HH24:MI:SS'),1,16)) FROM TestTable )
GROUP BY NAME
</code></pre>

<h1>Table Data</h1>

<pre><code>NAME    COL1   COL2    GATHER_TIME         VALUE
------------------------------------------------
first   prince PQ1     2015-12-29 13:10:33 11
first   prince PQ2     2015-12-29 13:10:33 14
first   prince PQ3     2015-12-29 13:10:33 18
first   prince PQ4     2015-12-29 13:10:33 19
second  prince TT1     2015-12-29 13:10:59 20
second  prince TT2     2015-12-29 13:10:59 29
second  prince TT3     2015-12-29 13:10:59 43
first   prince PQ1     2015-12-29 13:11:37 71
first   prince PQ2     2015-12-29 13:11:37 74
first   prince PQ3     2015-12-29 13:11:37 78
first   prince PQ4     2015-12-29 13:11:37 79
</code></pre>

<h1>Required result</h1>

<pre><code>@ Query time: 2015-12-29 13:10:59
first       62
second      92

@ Query time: 2015-12-29 13:11:59
first       302
second      92
</code></pre>

<h1>Added:</h1>

<p>Sorry. I should have put more detail test data. Updated it.</p>

<h1>If two columns are used in GROUP BY:: ( Need to be verified )</h1>

<pre><code>SELECT DISTINCT ON (name,col1,gather_time) name,col1,SUM(value) 
FROM test_table
GROUP BY name,col1,gather_time
ORDER BY gather_time DESC
LIMIT 2;
</code></pre>