Selecting rows ordered by some column and distinct on another

Quite a clear question 🙂 SELECT t1.* FROM purchases t1 LEFT JOIN purchases t2 ON t1.address_id = t2.address_id AND t1.purchased_at < t2.purchased_at WHERE t2.purchased_at IS NULL ORDER BY t1.purchased_at DESC And most likely a faster approach: SELECT t1.* FROM purchases t1 JOIN ( SELECT address_id, max(purchased_at) max_purchased_at FROM purchases GROUP BY address_id ) t2 ON … Read more

Get most common value for each value of another column in SQL

It is now even simpler: PostgreSQL 9.4 introduced the mode() function: select mode() within group (order by food_id) from munch group by country returns (like user2247323’s example): country | mode ————– GB | 3 US | 1 See documentation here: https://wiki.postgresql.org/wiki/Aggregate_Mode https://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-ORDEREDSET-TABLE

How do I limit the number of rows per field value in SQL?

Unluckily mysql doesn’t have Analytical Functions. So you have to play with variables. Supposing you have an autoincrement field: mysql> create table mytab ( -> id int not null auto_increment primary key, -> first_column int, -> second_column int -> ) engine = myisam; Query OK, 0 rows affected (0.05 sec) mysql> insert into mytab (first_column,second_column) … Read more

Select corresponding to row from the same table SQL Server

I’m not really smart from your description, however, the result can be achieved using the following query select your_table.* from your_table join ( select BlilShortName, max(billversion) bmax from your_table group by BlilShortName ) t on your_table.billversion = t.bmax and your_table.BlilShortName = t.BlilShortName From my experience it can be faster in some cases when compared to … Read more