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

标签 mysql hive query-optimization hiveql impala

我试图通过从两个不同的日期列中获取最大值来查询表,并输出具有两个日期最大值的所有记录

该表有6列,包括st_id(string)(同一id有多个条目)、as_of_dt(int)和ld_dt_ts(timestamp)。从这个表中,我试图获取 as_of_dt 和 ld_dt_ts 的最大值并按 st_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_of_dt 和 ld_dt_ts 最大值的 st_id,即每个 st_id 的最新记录。

最佳答案

使用分析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

最终连接不会返回任何行,因为不存在任何具有这种组合的行,而两个排名组合的查询将返回:

st_id, as_of_dt, ld_dt_ts 
1       2         1

如果您的数据中不存在这样的数据集(例如,ld_dt_ts 始终>=as_of_dt),那么您可以将排名合并为单个排名,甚至在排序依据中仅使用一个日期。

关于mysql - 如何在sql中检索表中两列的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56657156/

相关文章:

SQLite 查询的运行速度比 MS Access 查询慢 10 倍

php - 树莓派 phpmyadmin 500 错误

mysql在查找重复项时获取所有记录

php - 使用php在多行中插入表单值

php - 两个查询,两个不同的表,只有一个循环

hadoop - 配置单元限制查询外部表时扫描通过的文件列表

mysql - 无法使用 hive 中的电话号码前缀加入 hive 表

hive0.10.0 线程中的异常 "main"java.lang.NoSuchMethodError : org. apache.thrift.EncodingUtils.setBit(BIZ)B

Android sqlite 和多个查询

mysql - 笛卡尔积过多,导致查询运行速度变慢