如何检索sql中两列最大值的表值

h79rfbju  于 2021-06-24  发布在  Hive
关注(0)|答案(2)|浏览(301)

我试图通过从两个不同的日期列中获取最大值来查询一个表,并输出具有两个日期的最大值的所有记录
该表有6列,其中包括st_id(string)(有多个相同id的条目)、as_of_dt(int)和ld_dt_ts(timestamp)。从这个表中,我试图得到as\u of \u dt和ld\u dt的最大值,并按st\u id分组并显示所有记录。

这是完美的,但它不是真正的最佳

SELECT A.st_id, A.fl_vw, A.tr_record FROM db.tablename A 
INNER JOIN (
    SELECT st_id, max(as_of_dt) AS as_of_dt, max(ld_dt_ts) AS ld_dt_ts 
    From db.tablename 
    group by st_id
) B on A.st_id = B.st_id and A.as_of_dt = B.as_of_dt and A.ld_dt_ts= B.ld_dt_ts

--
预期结果应返回最大值为as\u of\u dt和ld\u dt的st\u id,即每个st\u id的最新记录。

jgwigjjp

jgwigjjp1#

使用分析 rank() 功能。 rank() 将分配 1 所有记录的最大日期 st_id 分区:

SELECT s.st_id, s.fl_vw, s.tr_record
from
(
SELECT A.st_id, A.fl_vw, A.tr_record,
       rank() over(partition by st_id order by as_of_dt desc) rnk_as_of_dt,
       rank() over(partition by st_id order by ld_dt_ts desc) rnk_ld_dt_tsrnk
  FROM db.tablename A 
)s 
WHERE rnk_as_of_dt=1 ANDrnk=1 rnk_ld_dt_ts=1 --get records with max dates in both columns

两个等级可以这样组合:

SELECT s.st_id, s.fl_vw, s.tr_record
from
(
SELECT A.st_id, A.fl_vw, A.tr_record,
       rank() over(partition by st_id order by as_of_dt desc, ld_dt_ts desc) rnk
  FROM db.tablename A 
)s 
WHERE rnk=1  --get records with max dates combination

但这与最初的查询不完全相同。例如,如果您有此数据集:

st_id, as_of_dt, ld_dt_ts 
1       1         2
1       2         1

那么这个查询

SELECT st_id, max(as_of_dt) AS as_of_dt, max(ld_dt_ts) AS ld_dt_ts 
    From db.tablename 
    group by st_id

将返回:

st_id, as_of_dt, ld_dt_ts 
1       2         2

final join不会返回任何行,因为不存在这样组合的行,而两个列组合的查询会返回:

st_id, as_of_dt, ld_dt_ts 
1       2         1

如果这样的数据集在您的数据中不存在(例如,ld\u dt \u ts总是>=as\u of \u dt),那么您可以将列组组合成单个列组,甚至可以按顺序使用一个日期。

bis0qfac

bis0qfac2#

--我正在使用row\ u number()函数--
行号()位于(按st\u id按as\u of \u dt desc,ld\u dt\u ts desc)rn from db.tablename s)tmp,其中rn=1

相关问题