Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For n=2 you could</p> <pre><code>SELECT max(column1) m FROM table t GROUP BY column2 UNION SELECT max(column1) m FROM table t WHERE column1 NOT IN (SELECT max(column1) WHERE column2 = t.column2) </code></pre> <p>for any n you could use approaches described <a href="http://explainextended.com/2009/03/10/analytic-functions-first_value-last_value-lead-lag/" rel="nofollow">here</a> to simulate rank over partition.</p> <p>EDIT: Actually <a href="http://explainextended.com/2009/03/06/advanced-row-sampling/" rel="nofollow">this</a> article will give you exactly what you need.</p> <p>Basically it is something like this</p> <pre><code>SELECT t.* FROM (SELECT grouper, (SELECT val FROM table li WHERE li.grouper = dlo.grouper ORDER BY li.grouper, li.val DESC LIMIT 2,1) AS mid FROM ( SELECT DISTINCT grouper FROM table ) dlo ) lo, table t WHERE t.grouper = lo.grouper AND t.val &gt; lo.mid </code></pre> <p>Replace <code>grouper</code> with the name of the column you want to group by and <code>val</code> with the name of the column that hold the values.</p> <p>To work out how exactly it functions go step-by-step from the most inner query and run them.</p> <p>Also, there is a slight simplification - the subquery that finds the <code>mid</code> can return NULL if certain category does not have enough values so there should be COALESCE of that to some constant that would make sense in the comparison (in your case it would be MIN of domain of the val, in article it is MAX).</p> <p><strong>EDIT2:</strong> I forgot to mention that it is the LIMIT 2,1 that determines the n (LIMIT n,1).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload