Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?
    primarykey
    data
    text
    <p><strong>My table is:</strong> </p> <pre><code>id home datetime player resource ---|-----|------------|--------|--------- 1 | 10 | 04/03/2009 | john | 399 2 | 11 | 04/03/2009 | juliet | 244 5 | 12 | 04/03/2009 | borat | 555 3 | 10 | 03/03/2009 | john | 300 4 | 11 | 03/03/2009 | juliet | 200 6 | 12 | 03/03/2009 | borat | 500 7 | 13 | 24/12/2008 | borat | 600 8 | 13 | 01/01/2009 | borat | 700 </code></pre> <p>I need to select each distinct <code>home</code> holding the maximum value of <code>datetime</code>. </p> <p><strong>Result would be:</strong> </p> <pre><code>id home datetime player resource ---|-----|------------|--------|--------- 1 | 10 | 04/03/2009 | john | 399 2 | 11 | 04/03/2009 | juliet | 244 5 | 12 | 04/03/2009 | borat | 555 8 | 13 | 01/01/2009 | borat | 700 </code></pre> <p><strong>I have tried:</strong></p> <pre><code>-- 1 ..by the MySQL manual: SELECT DISTINCT home, id, datetime AS dt, player, resource FROM topten t1 WHERE datetime = (SELECT MAX(t2.datetime) FROM topten t2 GROUP BY home) GROUP BY datetime ORDER BY datetime DESC </code></pre> <p>Doesn't work. Result-set has 130 rows although database holds 187. Result includes some duplicates of <code>home</code>.</p> <pre><code>-- 2 ..join SELECT s1.id, s1.home, s1.datetime, s1.player, s1.resource FROM topten s1 JOIN (SELECT id, MAX(datetime) AS dt FROM topten GROUP BY id) AS s2 ON s1.id = s2.id ORDER BY datetime </code></pre> <p>Nope. Gives all the records.</p> <pre><code>-- 3 ..something exotic: </code></pre> <p>With various results.</p>
    singulars
    1. This table or related slice is empty.
    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