Note that there are some explanatory texts on larger screens.

plurals
  1. POMysql limit rows per group weird results
    primarykey
    data
    text
    <p>I wanted to get the latest 4 dates for each <code>symbolid</code>. I adapted the code <a href="http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/" rel="nofollow noreferrer">here</a> as follows:</p> <pre><code>set @num := 0, @symbolid := ''; select symbolid, date, @num := if(@symbolid = symbolid, @num + 1, 1) as row_number, @symbolid := symbolid as dummy from projections group by symbolid, date desc having row_number &lt; 5 </code></pre> <p>and get the following results:</p> <pre><code>symbolid date row_number dummy 1 '2011-09-01 00:00:00' 1 1 1 '2011-08-31 00:00:00' 3 1 1 '2011-08-30 00:00:00' 5 1 2 '2011-09-01 00:00:00' 1 2 2 '2011-08-31 00:00:00' 3 2 2 '2011-08-30 00:00:00' 5 2 3 '2011-09-01 00:00:00' 1 3 3 '2011-08-31 00:00:00' 3 3 3 '2011-08-30 00:00:00' 5 3 4 '2011-09-01 00:00:00' 1 4 ... </code></pre> <p>The obvious question is, why did I only get 3 rows per <code>symbolid</code>, and why are they numbered 1,3,5? A few details:</p> <ol> <li>I tried both forcing an index and not (as seen here), and got the same results both ways. </li> <li>The dates are correct, i.e., the listing correctly shows the top 3 dates per <code>symbolid</code>, but the row_number value is off</li> <li>When I don't use the "having" statement, the row numbers are correct, i.e., the most recent date is 1, the next most recent is 2, etc</li> </ol> <p>Obviously the <code>row_number</code> computed field is being affected by the "having" clause, but I don't know how to fix it.</p> <p>I realize that I could just change the "having" to "having row_number &lt; 7" (6 gives the same as 5), but it's very ugly and would like to know what to do to make it "behave".</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. 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