我有两个表:task_runs
和integer_values
。我正在运行查询以获得此输出:
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
这是我查询的输出,它来自两个不同的表。请注意,在此输出中,task_name
发生了两次。但是我希望输出只出现一次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
我的查询是:
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
为什么不起作用?
答案 0 :(得分:1)
SELECT task_name, MAX(start_time) FROM your_table GROUP BY task_name;
分组依据将采用重复项并在此情况下将它们分组到task_name上。 MAX将采用最高值。 SO:当存在具有相同名称的更多任务时,显示一次并仅显示具有最高start_time的任务。
答案 1 :(得分:0)
答案 2 :(得分:0)
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
答案 3 :(得分:0)
;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