如何选择具有最大值的行?

时间:2019-01-13 11:01:36

标签: sql sqlite

鉴于此表,我想为每个不同的URL检索具有最大计数的行。对于此表,输出应为:'dell.html'3,'lenovo.html'4,'toshiba.html'5

+----------------+-------+
| url            | count |
+----------------+-------+
| 'dell.html'    |     1 |
| 'dell.html'    |     2 |
| 'dell.html'    |     3 |
| 'lenovo.html'  |     1 |
| 'lenovo.html'  |     2 |
| 'lenovo.html'  |     3 |
| 'lenovo.html'  |     4 |
| 'toshiba.html' |     1 |
| 'toshiba.html' |     2 |
| 'toshiba.html' |     3 |
| 'toshiba.html' |     4 |
| 'toshiba.html' |     5 |
+----------------+-------+

要执行此操作,我需要编写什么SQL查询?

2 个答案:

答案 0 :(得分:4)

尝试使用此查询:

select url, max(count) as count
from table_name
group by url;

答案 1 :(得分:1)

使用聚合函数

  select max(count) ,url from table_name group by url

从您的评论看来,您需要相关的子查询

select t1.* from table_name t1
 where t1.count = (select max(count) from table_name t2 where t2.url=t1.url
                 )

如果您的sqllite版本支持row_number 那么您可以编写如下查询

select * from 
(
select *,row_number() over(partition by url  order by count desc) rn
  from table_name
) a where a.rn=1