title: SQLAlchemy Order By before Group By
body: <p>I've researched a lot in terms of doing a query to do an <code>order by</code> before a <code>group by</code> and have found most answers in terms of <code>raw SQL</code>. However, I'd like to see a solution in <code>SQLAlchemy Code</code>.  </p>
  
  <ol>
  <li><p>My original naive solution looked as follows:</p>
  
  <pre><code>session.query(MyTable).order_by(timestamp).group_by(begin_date)
  </code></pre>
  
  <blockquote>
    <p>unfortunately, this causes the table to first be grouped then ordered, which will not return what I am expecting.</p>
  </blockquote></li>
  <li><p>Second,I tried:</p>
  
  <pre><code> stmt = session.query(MyTable).order_by(timestamp)
   session.query(stmt).group_by(begin_date)
  </code></pre>
  
  <blockquote>
    <p>This returns the correct results, however, the results are of <code>KeyedTuples</code> whereas I want to actually have MyTable objects for backwards compatibility reasons.</p>
  </blockquote></li>
  </ol>
  
  <p>How can I achieve this?</p>