2015-02-11 156 views
1

我試圖在結果集中獲得每個分組行的TOP 1結果。如何從這個GROUP BY結果中獲得TOP 1?

Id LogType CreatedOn 
=============================== 
1 Red  2000-01-02T12:34:56Z 
2 Red  2000-01-02T12:34:56Z 
3 Blue 2000-01-02T12:34:56Z 
4 Green 2000-01-02T12:35:56Z 
5 Red  2000-01-02T12:36:56Z 
6 Red  2000-01-02T12:37:56Z 
7 Blue 2000-01-02T12:38:56Z 
8 Green 2000-01-02T12:39:56Z 

預期結果

LogType Count MostRecent 
================================== 
Red  4  2000-01-02T12:37:56Z 
Blue 2  2000-01-02T12:38:56Z 
Green 2  2000-01-02T12:39:56Z 

This has all been setup in this Sql Fiddle

我得到了COUNT(這很容易),但我不知道如何獲得最新的,然後將其鏈接回以前的結果。我正在考慮ROW_NUMBER()/PARTITION ORDER BY CreatedOn DESC= 1篩選..但我堅持加入。

注意:如果對軟件特定關鍵字有任何疑問,我正在使用SQL Server 2012。

回答

1

使用Count() over(Partition by)訣竅做到這一點。

Over子句將幫助您找到每個group(LogType)的計數,然後如您所述,使用row_number窗口函數找到每組中的前1個。

select LogType, Count, MostRecent from 
(
select Row_number() over(partition by LogType order by CreatedOn DESC) RN, 
     Id, LogType, CreatedOn as MostRecent, 
     count(LogType) over(partition by LogType) [Count] 
     from yourtable 
) A 
where RN=1 

SQLFIDDLE DEMO

+0

TIL:你可以做一個'COUNT(..)OVER(PARTITION ...)'。我總是完成了'ROW_NUMBER()OVER..'。 :HI-5: – 2015-02-11 01:58:02

0

試試下面這段代碼:

select LogType, count(1) as 'Count', max(CreatedOn) as 'MostRecent' 
from yourtablename 
group by LogType 
order by Count desc