我有下表
表格产品:
PRO_ID PRO_Date PRO_Price
123 1/1/2016 2000
123 2/1/2016 2500
123 3/1/2016 1500
123 5/1/2016 3000
456 1/1/2016 2000
456 2/1/2016 2500
456 3/1/2016 1500
456 5/1/2016 3000
456 6/1/2016 3500
目前使用查询:
select PRO_ID, max(PRO_DATE) as Last_PRO_Date
from
(select PRO_ID, PRO_DATE from PRODUCT where PRO_DATE<='01-JUN-2016')
group by PRO_ID
目前获得的输出:
PRO_ID Last_PRO_Date
123 5/1/2016
456 6/1/2016
但现在我想要提供第二个最后日期。
预期产出/所需产出:
PRO_ID Last_PRO_Date Second_Last_PRO_Date
123 5/1/2016 3/1/2016
456 6/1/2016 5/1/2016
答案 0 :(得分:2)
您可以在没有子查询的情况下编写查询:
select PRO_ID, MAX(PRO_DATE) as Last_PRO_Date
from PRODUCT
where PRO_DATE <= '01-JUN-2016'
group by PRO_ID;
但是,对于前两个日期,我会使用dense_rank()
和聚合:
select PRO_ID,
max(casse when seqnum = 1 then PRO_DATE end) as Last_PRO_Date,
max(casse when seqnum = 2 then PRO_DATE end) as Second_Last_PRO_Date
from (select PRO_ID, PRO_DATE,
dense_rank() over (partition by PRO_ID order by PRO_DATE desc) as seqnum
from PRODUCT
where PRO_DATE <= '01-JUN-2016'
) t
group by PRO_ID;