我有一张包括这些栏的表格:
样本数据:
concurrent_users concurrent_timestamp concurrent_date
3 2020-06-24 07:20:00 UTC 2020-06-24
7 2020-06-24 08:20:00 UTC 2020-06-24
8 2020-07-05 06:20:00 UTC 2020-07-05
2 2020-07-05 03:20:00 UTC 2020-07-05date.的concurrent_users最高的日期和时间戳。
预期产出:
concurrent_users concurrent_timestamp concurrent_date
7 2020-06-24 08:20:00 UTC 2020-06-24
8 2020-07-05 06:20:00 UTC 2020-07-05我尝试了以下方法/查询:
select concurrent_timestamp, max(concurrent_users)
from sample_data
group by concurrent_date;但这会产生一个错误,因为concurrent_timestamp列不包含在group by子句中。
当我把concurrent_timestamp放进group by的时候,我.
select concurrent_timestamp, max(concurrent_users)
from sample_data
group by concurrent_timestamp ;它没有给出所需的输出,而只是列出了每个date的多个记录。
如何解决这个问题?
发布于 2020-07-22 00:27:45
在PostgreSQL中,您只需使用DISTINCT ON:
SELECT DISTINCT ON (concurrent_date) *
FROM sample_data
ORDER BY concurrent_date, concurrent_users DESC;我们根本不需要冗余列concurrent_date。动态转换concurrent_timestamp非常便宜--总体上比冗余存储功能相关的值更便宜。
SELECT DISTINCT ON (concurrent_timestamp::date) *
FROM sample_data
ORDER BY concurrent_timestamp::date, concurrent_users DESC;db<>fiddle 这里
请参见:
DISTINCT ON是通常是最快的每组行。根据表定义和数据分布,可能有(更快)更快的解决方案。请参见:
发布于 2020-07-21 22:21:18
这是一个“群智-最大”的问题。您不能用简单的查询来完成它,您需要一个子查询。我添加的标记中有许多示例。或者你可以读我的博客:http://mysql.rjweb.org/doc.php/groupwise_最大值
发布于 2020-07-22 01:19:40
只需将日期()函数应用于concurrent_timestamp的聚合
select
DATE(concurrent_timestamp) timestamp_date
,max(concurrent_users) max_concurrent_users
from sample_data
group by DATE(concurrent_timestamp);https://dba.stackexchange.com/questions/271381
复制相似问题