PostgreSQL MAX和GROUP BY

前端之家收集整理的这篇文章主要介绍了PostgreSQL MAX和GROUP BY前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。



我有一个id,年和数的表.

我想得到每个id的MAX(count),并保持发生的一年,所以我做这个查询

  1. SELECT id,year,MAX(count)
  2. FROM table
  3. GROUP BY id;@H_404_14@
  4. 不幸的是,它给我一个错误

  5. ERROR: column table.year must appear in the GROUP BY clause or be
    used in an aggregate function

  6. 所以我试试:

  7. SELECT id,MAX(count)
  8. FROM table
  9. GROUP BY id,year;@H_404_14@ 
  10.  

    但是,它不做MAX(计数),它只是显示表.我想,因为当按年份和身份分组时,它会获得该特定年份的最大值.

  11.  

    那么,怎么写这个查询呢?我想得到IDMAX(计数)和发生的那一年.

@H_403_33@
  1. select *
  2. from (
  3. select id,thing,max(thing) over (partition by id) as max_thing
  4. from the_table
  5. ) t
  6. where thing = max_thing@H_404_14@
  7. 要么:

  8. select t1.id,t1.year,t1.thing
  9. from the_table t1
  10. where t1.thing = (select max(t2.thing) 
  11.                   from the_table t2
  12.                   where t2.id = t1.id);@H_404_14@ 
  13.  

    要么

  14.   
  15.  
    select t1.id,t1.thing
  16. from the_table t1
  17.   join ( 
  18.     select id,max(t2.thing) as max_thing
  19.     from the_table t2
  20.     group by id
  21.   ) t on t.id = t1.id and t.max_thing = t1.thing@H_404_14@ 
  22.  

    或(与以前的不同符号相同)

  23.   
  24.  
    with max_stuff as (
  25.   select id,max(t2.thing) as max_thing
  26.   from the_table t2
  27.   group by id
  28. ) 
  29. select t1.id,t1.thing
  30. from the_table t1
  31.   join max_stuff t2 
  32.     on t1.id = t2.id 
  33.    and t1.thing = t2.max_thing@H_404_14@

猜你在找的Postgre SQL相关文章