我需要能够按两列进行分组,并且仅返回这两列的另一列的 id 为最大值的行。我想要的详细信息在第四列中,称为答案
COLUMN1 | COLUMN2 | NUMBERCOL | Answer
--------------- ----------------------------
123 | 456 | 1 | a
123 | 456 | 2 | x
123 | 456 | 3 | s
654 | 564 | 1 | a
654 | 564 | 2 | s
654 | 564 | 3 | p
654 | 564 | 4 | b
所以我需要第一个分组结果中的答案 s 和第二个分组结果中的答案 b
最佳答案
您可以使用带有 JOIN
的子查询来获取结果:
select t1.column1,
t1.column2,
t1.numbercol,
t1.answer
from yourtable t1
inner join
(
select column1, column2,
max(numbercol) MaxNum
from yourtable
group by column1, column2
) t2
on t1.column1 = t2.column1
and t1.column2 = t2.column2
and t1.numbercol = t2.MaxNum
关于sql - 按两列和另一列的最大值分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15007338/