返回 Spark SQL 找到的 Min 和 Max()row_number

问题描述 投票:0回答:1
select distinct 
snap1.rn,
snap2.rn1,
snap1.doc_num


from (select DISTINCT *,
row_number() over (partition by car_id order by SNAPSHOT_DATE, CAR_ID) rn
from MY_TABLE
)snap1 


left join 
(select DISTINCT *,
row_number() over (partition by car_id order by SNAPSHOT_DATE, CAR_ID) rn1
from MY_TABLE
)snap2 
on snap1.CAR_ID = snap2.CAR_ID

where snap1.DOC_NUM = '73927243'
and snap1.rn = '1'

我想检索 1 条记录,其中包含第一个和最后一个记录,例如RN = 1 且 RN1 = 12。
不是其他人的记录。 注意:最大值并不总是 12,可能是 10、11 等。

已尝试 max(rn1) 但它仍然返回所有 12 行。

一旦我可以获得第一个和最后一个记录,我会将其扩展到所有 doc_num。所以我不能使用“限制 1”。

sql apache-spark max min
1个回答
0
投票

您可以选择以相反顺序排序的第一行:

select  *
from    (
        select  row_number() over (partition by car_id
                        order by snapshot_date) rn1
        ,       row_number() over (partition by car_id
                        order by snapshot_date desc) rn2
        ,       *
        from    MY_TABLE
        ) sub
where   rn1 = 1 or rn2 = 1
© www.soinside.com 2019 - 2024. All rights reserved.