Note that there are some explanatory texts on larger screens.

plurals
  1. POis this a candidate for a sql groupby query?
    primarykey
    data
    text
    <p>I have two tables: <strong>TableA</strong> (<code>ID [int, pk], Name [string])</code> and <strong>TableB</strong> <code>(ID [int, pk], TableA_ID [int, fk], Name [string], DateStamp [datetime (dd/mm/yyyy hh:MM:ss)])</code>. There is a one-to-many relationship between TableA and TableB.</p> <p>An inner join on the two tables will give me the following results:</p> <pre> TableA.ID, TableA.Name, TableB.Name, TableB.DateStamp 1, 'File A', 'Version 1', 01/01/2009 15:00:00 1, 'File A', 'Version 2', 05/01/2009 08:15:00 1, 'File A', 'Version 3', 06/01/2009 19:33:00 2, 'File B', 'Version 1', 03/01/2009 09:10:00 2, 'File B', 'Version 2', 20/01/2009 20:00:00 3, 'File C', 'Version 1', 01/01/2009 17:00:00 </pre> <p>What I actually want is the following (each row from TableA and the last matching row from TableB):</p> <pre> TableA.ID, TableA.Name, TableB.Name, TableB.DateStamp 1, 'File A', 'Version 3', 06/01/2009 19:33:00 2, 'File B', 'Version 2', 20/01/2009 20:00:00 3, 'File C', 'Version 1', 01/01/2009 17:00:00 </pre> <p>This is the query that I'm using to achieve this:</p> <pre><code>SELECT ta.ID, ta.Name, tb.Name, tb.DateStamp FROM TableA ta INNER JOIN TableB tb ON ta.ID = tb.TableA_ID WHERE tb.ID IN ( SELECT TOP 1 tb2.ID FROM TableB tb2 WHERE tb2.TableA_ID = ta.ID ORDER BY tb2.DateStamp DESC) </code></pre> <p>That works but my gut feeling is that I'm not doing this in the "best way". It looks like it is a candidate for an aggregation query (i.e. groupby) but I didn't have any luck with that. In the end I always had to use a subquery to get the row I'm after in TableB.</p> <p>Any help much appreciated.</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.
 

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