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?????????
为什么我的查询无效?
我的值来自两个表:task_runs,integer_value。我想要这三个列,但是任务名称与max start_time相关联,并与其值相关联。
答案 0 :(得分:2)
您当前的陈述有两个问题
ORDER BY
必须在 GROUP BY
i.value
子句中添加GROUP BY
或在i.value
上使用聚合函数(MIN,MAX,AVG,...) 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'
group by
t.task_name
, i.value
order by
t.task_name
select t.task_name
, t.start_time
, i.value
from (
select t.task_name
, start_time = max(t.start_time)
from task_runs t
where t.username= 'amit'
and t.start_time > '2010-05-20'
group by
t.task_name
) tm
INNER JOIN task_runst t ON t.task_name = tm.task_name AND t.start_time = tm.start_time
INNER JOIN integer_values i ON i.run_id = t.id
order by
t.task_name
答案 1 :(得分:0)
GROUP BY
必须在ORDER BY
之前,您应该选择i.value
的值(最大,最小,......)。
答案 2 :(得分:0)
在MSSQL上试试这个
SELECT t.id
, MAX(t.task_name) AS task_name
, MAX(t.start_time) AS start_time
, (SELECT TOP 1 value FROM integer_values WHERE run_id = t.id) AS value
FROM task_runs t
WHERE t.username = 'amit'
AND t.start_time > '20100520'
GROUP BY t.id
ORDER BY task_name