问题:
表A
NAME DATE COL1
------------------------------
A 2011/06/07 4
A 2011/06/09 6
A 2011/06/03 7
B 2011/06/29 5
B 2011/06/30 6
求查询出每个NAME下的日期最大的结果
NAME DATE COL1
------------------------------
A 2011/06/09 6
B 2011/06/30 6
WITH a AS (
SELECT 'A' NAME,'2011/06/07' "DATE",'4' COL1 FROM dual UNION ALL
SELECT 'A' NAME,'2011/06/09' "DATE",'6' COL1 FROM dual UNION ALL
SELECT 'A' NAME,'2011/06/03' "DATE",'7' COL1 FROM dual UNION ALL
SELECT 'B' NAME,'2011/06/29' "DATE",'5' COL1 FROM dual UNION ALL
SELECT 'B' NAME,'2011/06/30' "DATE",'6' COL1 FROM dual
)
--方法一
SELECT NAME,"DATE",COL1 FROM
(SELECT NAME,"DATE",COL1,row_number() over (partition by NAME order by "DATE" desc) rn FROM a)
WHERE rn=1
;
--方法二
select NAME,max("DATE"),max(COL1)keep(dense_rank first order by "DATE" desc) col1
from a
group by name;
方法一
常规分析函数。
ROW_NUMBER :返回有序组中一行的偏移量,从而可用于按特定标准排序的行号
方法二
first / last从DENSE_RANK返回的集合中取出排在最前面(后面)的一个值的行(可能多行,因为值可能相等),因此完整的语法需要在开始处加上一个集合函数以从中取出记录