我有一张idyearcount的桌子.

我想得到每个idMAX(count),并在发生时保留year,因此我提出以下查询:

SELECT id, year, MAX(count)
FROM table
GROUP BY id;

不幸的是,它给了我一个错误:

错误:列"table.year"必须出现在GROUP BY子句中,或者

所以我试着:

SELECT id, year, MAX(count)
FROM table
GROUP BY id, year;

但是,它不会显示MAX(count),它只是显示表格的原样.我想是因为当按yearid分组时,它得到了该特定年份id的最大值.

那么,我该如何编写这个查询呢?我想拿到id分的MAX(count)分,以及那一年的成绩.

推荐答案

select *
from (
  select id, 
         year,
         thing,
         max(thing) over (partition by id) as max_thing
  from the_table
) t
where thing = max_thing

或者:

select t1.id,
       t1.year,
       t1.thing
from the_table t1
where t1.thing = (select max(t2.thing) 
                  from the_table t2
                  where t2.id = t1.id);

select t1.id,
       t1.year,
       t1.thing
from the_table t1
  join ( 
    select id, max(t2.thing) as max_thing
    from the_table t2
    group by id
  ) t on t.id = t1.id and t.max_thing = t1.thing

或 (same as the previous with a different notation)

with max_stuff as (
  select id, max(t2.thing) as max_thing
  from the_table t2
  group by id
) 
select t1.id, 
       t1.year,
       t1.thing
from the_table t1
  join max_stuff t2 
    on t1.id = t2.id 
   and t1.thing = t2.max_thing

Sql相关问答推荐

使用自动增量ID插入失败(无法将值空插入列ID)

Postgresql -如何计算刷卡和刷卡时间

将SEMI JOIN、ANTI JOIN转换为非连接SQL

GROUP BY与多个嵌套查询T—SQL

查询多个表并返回合并在联合列上的所有表中的所有行

如何在SQL中按每个子组的顺序更新数据?

对任何(数组)使用LIKE?

如何嵌套两条SQL语句

UPDATE查询中的乐观锁

如何将不同层次的产品组和规格组合到最深一层?

使用特定的Order By子句随机化SQL输出

将时间范围划分为全天和前后剩余小时

根据标识符将两行合并为一行

确定小数中使用的精度位数

Oracle 21c 中的递归查询回顾过go 3 周

SQL ORACLE - 查找连续天数

为数组中的每个元素从表中收集最大整数

如何将多行的查询结果合并为一行

有没有一种方法可以将始终遵循序列的单个字段的值组合起来,以创建每个 ID 的所有移动?

当计数为 0 时显示行