如何从GROUP BY结果中获得TOP 1?

时间:2015-02-11 01:39:45

标签: sql group-by sql-server-2012

我正在尝试在结果集中为每个分组行获取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.

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

请尝试以下代码:

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