首页 > 解决方案 > 仅获取第一行或最高值 SQL

问题描述

我正在尝试获取第一行(也是此查询的最高值)它现在正在发布所有内容

例如,当我尝试添加 Limit/NumRow 以获取第一行(也是最高值)时,它会导致查询出错。查询是

select
  title
, min(year)
, max(year)
, count(appointment) AS num_appointments 
from appointments 
group by title 
ORDER BY title 
ORDER BY count(title) desc;

标签: sql

解决方案


您可以尝试以下方法 - 限制适用于MySql/Postgres

select title, min(year), max(year), 
count(appointment) AS num_appointments 
from appointments group by title 
ORDER BY count(appointment) desc
limit 1

如果您的数据库是 SQL Server - 您可以使用 TOP 如下所示 -

select TOP 1 title, min(year), max(year), 
    count(appointment) AS num_appointments 
    from appointments group by title 
    ORDER BY count(appointment) desc
    

推荐阅读