从SQL Server中的group-by子句中包含不同字符串值的结果中获取最大值



我的表是这样的,

Field1   |  Field2  |  Field3
2        |    100   |  test1
3        |    100   |  test2

我需要从这个结果中得到最大值。因此结果应该如下,

3   100   test2

我目前的查询是

SELECT MAX(Field1),Field2,Field3 FROM Table1 GRUOP BY Field2,Field3

这将返回这两行。但是我只需要包含CCD_ 1值的行。

假设您想要的行对于每个不同的field2具有最大的field1。由于您需要整行,因此聚合不是解决方案;相反,您希望进行筛选。

这里有一种使用相关子查询的方法:

select t.*
from mytable t
where t.field1 = (select max(t1.field1) from mytable t1 where t1.field2 = t.field2)

另一个选项使用窗口功能:

select *
from (
select t.*, rank() over(partition by field2 order by field1 desc) rn
from mytable t
) t
where rn = 1

最后,这里有一个使用with ties:的更新颖的方法

select top (1) with ties *
from mytable
order by rank() over(partition by field2 order by field1 desc)

最新更新