Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

SELECT DISTINCT ON (album_id) * FROM tracks GROUP BY album_id ORDER BY milliseconds DESC;

For those unfamiliar with Postgres, DISTINCT ON takes only one row for each of the groups based on the supplied columns. So in this case, it will return only one row per album_id.

Without an ORDER BY, DISTINCT ON chooses a random row (not actually, but you can’t rely on it.) Since we ORDER BY milliseconds DESC, the first row of each group will be the longest one.



that works for top-1 but breaks completely if you want to extend it to top-2


The example was asking for top 1. Yes, you are correct that you'd have to switch up to a window function to handle top-n+1.

Do you believe these cases are common enough to warrant discarding the tools and training available to SQL? Are you also certain that PRQL doesn't have corner cases where SQL is more concise and/or easier to understand?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: