Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I can see how this might be a problem if you want to ORDER BY variables that you are not wanting to GROUP BY. Not including certain variables in your GROUP BY statement would eliminate those columns FROM the resultant table, and hence you would not be able to order it by them.</p> <p>In your example, you might want to show how many times a given Pokemon had a certain status, like so:</p> <pre><code>SELECT p.name ,d.status ,count(*) tally FROM pokemon p INNER JOIN pokedex d on p.name=d.id GROUP BY p.name ,d.status </code></pre> <p>You couldn't order the above query result by 'age' since you didn't GROUP BY name, status, <em>and</em> age.</p> <p>In this example, I would do:</p> <pre><code>SELECT p.age ,p.name ,d.status ,count(*) tally FROM pokemon p INNER JOIN pokedex d on p.name=d.id GROUP BY p.age ,p.name ,d.status </code></pre> <p><strong>However</strong>, and to your point, it is not always possible to include in the 'group by' clause those columns you would want to order the data by. So, taking your Pokemon data/tables as my example let me illustrate a general approach that might be helpful:</p> <p><strong>1)</strong> First, I would create a table with my custom ordering:</p> <pre> SELECT * ,ROW_NUMBER() as my_order FROM ( SELECT age ,name FROM pokemon ORDER BY age ,name ) </pre> <p><strong>2)</strong> Then, I'd join it to the rest of my grouped table, ordering by the custom 'my_order' column I had created for this purpose:</p> <pre> SELECT a.* ,custom.my_order FROM a -- I'm calling 'a' your table, after your joins/group bys INNER JOIN ( SELECT name ,ROW_NUMBER() as my_order FROM ( SELECT age ,name FROM pokemon ORDER BY age ,name ) ) AS custom ON a.name=custom.name ORDER BY custom.my_order </pre> <p>This is my version of <em>'grouping after doing an ordering'</em>, though I don't think about it in those terms - I think of it as a 'custom' ordering.</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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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