我有一个表名batch_log,其结构如下
batch_id run_count start_date end_date
1 4 03/12/2014 03/12/2014
1 3 02/12/2014 02/12/2014
1 2 01/12/2014 01/12/2014
1 1 30/11/2014 30/11/2014
2 5 03/12/2014 03/12/2014
2 4 02/12/2014 02/12/2014
2 3 01/12/2014 01/12/2014
2 2 30/11/2014 30/11/2014
2 1 29/11/2014 29/11/2014
3 3 02/12/2014 02/12/2014
3 2 01/12/2014 01/12/2014
3 1 30/11/2014 30/11/2014
我需要使用max run_count获取所有batch_id的行。 查询结果应为:
batch_id run_count start_date end_date
1 4 03/12/2014 03/12/2014
2 5 03/12/2014 03/12/2014
3 3 02/12/2014 02/12/2014
我尝试了很多选项,group by batch_id和run_count但无法获得正确的结果
select a.* from batch_log a,batch_log b
where a.batch_id =b.batch_id
and a.run_count=b.run_count
and a.run_count in (select max(run_count) from batch_log
group by batch_id ) order by a.batch_id
请求帮助
答案 0 :(得分:4)
select *
from(
select a.*, max(run_count) over (partition by batch_id) max_run_count
from batch_log a)
where run_count=max_run_count;
答案 1 :(得分:1)
这也应该有效:
SELECT * FROM batch_log b1
WHERE b1.run_count = (SELECT max(b2.run_count)
FROM batch_log b2
WHERE b2.batch_id = b1.batch_id
GROUP BY b2.batch_id)
答案 2 :(得分:0)
您可以通过此查询执行此操作:
select *
from batch_log a
inner join (
select b.batch_id , max(run_count) as run_count
from batch_log b
group by b.batch_id
) c on a.batch_id = c.batch_id and a.run_count = c.run_count
希望有所帮助
答案 3 :(得分:0)
Arion给出的答案看起来很完美。您可以按照以下修改,以达到您的确切要求
SELECT batch_id,run_count,start_date,end_date
FROM
(
SELECT
ROW_NUMBER() OVER(PARTITION BY batch_id ORDER BY run_count DESC) AS RowNbr,
batch_log.*
FROM
batch_log
) as batch
WHERE
batch.RowNbr=1