简体   繁体   English

SQL:如何选择每天的最大记录?

[英]SQL: How to select a max record each day?

在此处输入图片说明

I found a lot of similar questions but no one fits perfectly for my case and I am struggling for hours for a solution.我发现了很多类似的问题,但没有一个完全适合我的情况,我正在努力寻找解决方案几个小时。 My table is composed by the fields DAY, HOUR, EVENT1, EVENT2, EVENT3.我的表由字段 DAY、HOUR、EVENT1、EVENT2、EVENT3 组成。 Therefore I have 24 rows each day.因此我每天有 24 行。 EVENT1, EVENT2, EVENT3 have some values and I'd like to select each day only the row (I mean the record) for which EVENT3 has the maximum value in the day (among the 24 hours). EVENT1、EVENT2、EVENT3 有一些值,我想每天只选择 EVENT3 在当天(24 小时内)具有最大值的行(我的意思是记录)。 The final outcome will be one row per day最终结果将是每天一行

源表

One method uses a correlated subquery:一种方法使用相关子查询:

select t.*
from t
where t.event3 = (select max(t2.event3)
                  from t t2
                  where t2.date = t.date
                 );

In most databases, this has very good performance with an index on (date, event3) .在大多数数据库中,这在(date, event3)上有索引时具有非常好的性能。

A more canonical solution uses row_number() :更规范的解决方案使用row_number()

select t.*
from (select t.*,
             row_number() over (partition by date order by event3 desc) as seqnum
      from t
     ) t
where seqnum = 1;

Another option aside from using correlated subqueries is to write this is a left self-join, something like this:除了使用相关子查询之外,另一种选择是编写这是一个左自连接,如下所示:

SELECT t.*
FROM t
LEFT JOIN t AS t2 ON t.day = t2.day AND t2.event3 > t.event3
WHERE t2.id IS NULL

If you want to select an arbitrary matching row each day in the event of multiple rows with the same maximum event3, tack GROUP BY t.day on the end of that.如果您想在具有相同最大 event3 的多行的情况下每天选择任意匹配的行, GROUP BY t.day在其末尾添加GROUP BY t.day

I'm not sure how performance of this is going to compare to Gordon Linoff's solutions, but they might get assembled into quite similar query plans by the RDBMS anyway.我不确定这与 Gordon Linoff 的解决方案的性能相比如何,但无论如何它们可能会被 RDBMS 组合成非常相似的查询计划。

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

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