Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it possible to do a GROUP BY in SQL Server 2000 that returns the whole row?
    primarykey
    data
    text
    <p>I have an SQL Server 2000 database that contains a view that shows meter readings for supply points which has the following columns:</p> <pre><code>- rh_sp_number &lt;- the number of the supply point - rh_... &lt;- a bunch of other columns pertaining to that specific reading row - rh_end_date &lt;- a `DateTime`field that holds the date of the reading </code></pre> <p>Each SupplyPoint can have 0..N readings. I need to fetch the last submitted row for any given SupplyPoint. And I want to accomplish this with <b>one</b> query to the Database.</p> <p>I need to do something like this:</p> <pre><code>var q = db.READINGS_HISTORY.Where(rh =&gt; ids.Contains(rh.rh_sp_number)) .GroupBy(rh =&gt; rh.rh_sp_number, rh =&gt; rh, (key, values) =&gt; values.OrderByDescending(rh =&gt; rh.rh_end_date).FirstOrDefault()) .ToList(); </code></pre> <p>In human language I need to select the last row of each group and return that row. Running this query (or any other combination that I could think of) will result in this:</p> <blockquote> <p>The execution of this query requires the APPLY operator, which is not supported in versions of SQL Server earlier than SQL Server 2005.</p> </blockquote> <p>I need to accomplish this in SQL Server 2000.</p> <p>It does not have to be a 'Group By' expression; anything that will return a maximum row for a given key will do.</p> <p><b>My solution:</b></p> <p>Based on Aarons answer I ended up with this query that does what I need (with a caveat, but business rules remove it form the equation for me).</p> <p>The caveat: <b>if there are same dates for same SupplyPoints the sql server will decide which row to choose</b></p> <pre><code>var hists = db.READINGS_HISTORY.Where(rh =&gt; ids.Contains(rh.rh_sp_number)) .GroupBy(rh =&gt; rh.rh_sp_number, rh =&gt; rh, (key, values) =&gt; new { key, date = values.Max(rh =&gt; rh.rh_end_date) }) .Join(db.READINGS_HISTORY, g =&gt; new { sp = g.key, date = g.date }, rh2 =&gt; new { sp = rh2.rh_sp_number, date = rh2.rh_end_date }, (g, rh) =&gt; rh) .Select(rh =&gt; new LastReading { //omitted.. }).ToList(); </code></pre>
    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