简体   繁体   English

如何从SQL查询的输出中获取最大值

[英]How to get maximum value from output of SQL query

I have two tables: task_runs and integer_values . 我有两个表: task_runsinteger_values I am running a query to get this output: 我正在运行查询以获取以下输出:

task_name         start_time            value
acc_clock         2010-05-27              4
icc_opy           2010-05-28              5
icc_dtaf          2010-05-29              3
acc_clock         2010-05-25             34
icc_ruty          2010-05-23             33
icc_ruty          2010-05-22             45

This is my output of a SQL query which is coming from two different tables. 这是来自两个不同表的SQL查询的输出。 Note that in this output, task_name is occuring twice. 请注意,在此输出中, task_name出现了两次。 But I want the output to have only one occurrence of task_name and its associated value should be the maximum start_time , like this: 但我希望输出仅出现一次task_name并且其关联值应为最大start_time ,如下所示:

task_name         start_time            value
icc_opy           2010-05-28              5
icc_dtaf          2010-05-29              3
acc_clock         2010-05-25             34
icc_ruty          2010-05-23             33

My query is: 我的查询是:

select t.task_name, max(t.start_time), i.value
from task_runs t, integer_values i
where i.run_id = t.id
and t.username = 'amit'
and t.start_time > '2010-05-20'
order by t.task_name
group by t.task_name

Why doesn't it work? 为什么不起作用?

SELECT task_name, MAX(start_time) FROM your_table GROUP BY task_name;

Group by will take duplicates and group them in this case on task_name. 分组依据将获取重复项,并在这种情况下将它们分组在task_name上。 And MAX will take the highest value. MAX将取最高值。 SO: when more tasks exist with the same name, display it once and show only the one with the highest start_time. 因此:当存在更多同名任务时,将其显示一次,仅显示具有最高start_time的任务。

我认为您需要看一下GROUP BYMAX

SELECT * FROM yourTable y
JOIN 
 (select task_name, MAX(start_time) maxtime FROM yourTable GROUP BY task_name) highest
ON y.task_name = highest.task_name AND y.start_time = highest.start_time
;WITH max_start AS
(
SELECT 
task_name
,start_time
,value
,row_number() OVER (PARTITION BY taskname ORDER BY start_time DESC) as row
FROM your_table
)
SELECT 
task_name
,start_time
,value
FROM max_start 
WHERE row = 1

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

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