如何根据具有最大值的列过滤行?

时间:2019-06-28 12:06:24

标签: sql greatest-n-per-group

我有一张桌子,如下表

--------Table 1----------
ID     VERSION     STATUS
001       1          1
001       1          2
002       1          3
002       2          4
002       2          3        

因此,在这里我需要根据版本和状态的最大值来过滤ID。预期结果低于

--------Table 1----------
ID     VERSION     STATUS
001       1          2
002       2          4

我尝试使用代码

select * 
from "table1" 
where "VERSION" = (select max("VERSION") from  "table1") 
  and "STATUS" = (select max("STATUS") from "table1")

但是它不起作用。请帮助

5 个答案:

答案 0 :(得分:1)

除非我缺少明显的内容,否则使用max进行简单分组可以做到:

SELECT ID, MAX(VERSION) As Version, MAX(STATUS) As Status
FROM table1
GROUP BY ID

答案 1 :(得分:1)

select id,max(version),max(status) from 
table1
group by id

答案 2 :(得分:0)

大多数dbms支持row_number(),您可以尝试如下操作

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

答案 3 :(得分:0)

您可以使用row_number()

select t.*
from (select t.*,
             row_number() over (partition by id order by version desc, status desc) as seqnum
      from t
     ) t
where seqnum = 1;

答案 4 :(得分:0)

尝试一下:

select id,version,status from (
select *,ROW_NUMBER() over (partition by id order by status desc) rn from YOURTABLE
) t
where rn=1