繁体   English   中英

SQL:如何分组并获取两个不同列的最大值

[英]SQL: How to group by and get the max of two different columns

这是我第一次发帖,所以我可能违反了所有格式规则。这是我的表格的一个例子

    product     category  cost  date(in julian)       time(in julian)
    -----------------------------------------------------------------
    1            222      12      120223                125418
    1            222      32      120223                125645
    1            222      11      120112                145411

我正在尝试按产品和类别进行分组,并获取最近创建的成本。

举个例子,在这种情况下,我想撤回 32。我在日期和时间上都做了一个最大值,我相信你知道我得到的最大日期是 120223(好),但是最大时间为 145411(坏)。

如何获取最大日期记录(留下所有 120223 条记录),然后获取这些记录的最大时间?

这是我一直在努力的一个例子:

select product, category, max(date), max(time)
from t1
group by product, category

一种方法是相关子查询:

select t1.*
from t1
where t1.time = (select max(tt1.time)
                 from t1 tt1
                 where tt1.product = t1.product and tt1.category = t1.category
                );
select *
from 
(
    select product, category, cost, date, time, row_number() over (partition by product, category order by date desc, time desc) as rn 
    from t1
) t0
where rn = 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM