Get row with biggest column value when there are similar rows?
I'm working on a system to add Tags to my site, right now this is my "Tags" table:
URL | Tag | UID
example1.com humor 123
example1.com humor 342
example1.com humor 234
example1.com blog 123
example1.com blog 432
example1.com food 221
example2.com blog 432
I'm using the following query to sum tags for each site:
SELECT *, COUNT(*) as SUM
FROM History
GRO开发者_如何学JAVAUP BY URL, UID
So I get:
URL | Tag | Sum
example1.com humor 3
example1.com blog 2
example1.com food 1
example2.com blog 1
Finally (and this is what I don't know how to do) I need to get only the 2 rows with the biggest Sum for each grouped URL so I know what's the actual subject of the site:
URL | Tag | Sum
example1.com humor 3
example1.com blog 2
example2.com blog 1
How can I do this?
Try using a self-join on your results. This article has some great examples. Rather than nesting a number of queries, it might be easier (and faster) to create a temporary table from your first query, and then using that for the second step (getting the max "sum" from each group). See the section of that page titled "Select the top N rows from each group".
精彩评论