如何基于多个字段并按多个字段分组选择最大值

时间:2018-07-03 10:50:32

标签: sql group-by max multiple-columns

请协助以下事项。 样本数据:

LOCATION    ITEMNO  TRANSDATE   DAYENDSEQ   ENTRYSEQ    LINENO  ANSWER
Area1       A       20180702    1           1           1       a
Area1       A       20180703    1           1           1       b
Area1       A       20180703    2           1           1       c
Area1       A       20180703    2           2           1       d
Area1       A       20180703    2           2           2       e
Area1       B       20180703    1           1           1       f
Area1       C       20180703    1           1           2       g
Area1       C       20180703    1           1           1       h
Area2       A       20180703    1           2           1       i
Area2       A       20180703    1           1           4       j
Area2       A       20180703    1           1           5       k

要返回每个位置每个项目的ANSWER值,其中TRANSDATE,DAYENDSEQ,ENTRYSEQ和LINENO(按此顺序)的组合最大。

LOCATION    ITEMNO  TRANSDATE   DAYENDSEQ   ENTRYSEQ    LINENO  ANSWER
Area1       A       20180703    2           2           2       e
Area1       B       20180703    1           1           1       f
Area1       C       20180703    1           1           2       g
Area2       A       20180703    1           2           1       i

1 个答案:

答案 0 :(得分:3)

使用ANSI标准的row_number()函数:

select t.*
from (select t.*,
             row_number() over (partition by location, itemno 
                                order by transdate desc, dayendseq desc, entryseq desc, lineno desc
                               ) as seqnum
      from t
     ) t
where seqnum = 1;