2014-12-03 25 views
0

我有一個表名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 

我需要爲所有最大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 

我試着用很多選項,通過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

http://stackoverflow.com/questions/27185746/how-to-get-latest-two-rows-with-certain-value-by -date-in-sql或http://stackoverflow.com/questions/27011494/group-by-with-maxtimestamp或http://stackoverflow.com/questions/3491329/group-by-with-maxdate – 2014-12-03 08:36:45

回答

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; 
+0

這工作正常 – dramixx 2014-12-03 08:56:22

+1

你應該學習使用,它真的解決了大部分這些問題。 – 2014-12-03 09:00:15

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) 
+0

這工作正常 – dramixx 2014-12-03 08:55:57

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 

希望它有助於阿里昂給出

0

答案是尋找完美的我。您可以修改此爲每低於實現您的具體要求

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