我怎样才能从这个 GROUP BY 结果中获得 TOP 1?
How can I get the TOP 1 from this GROUP BY result?
我正在尝试为我的结果集中的每个分组行获取前 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
(这很容易),但我不确定如何获取最新的然后 link 返回到以前的结果。我在考虑 ROW_NUMBER() / PARTITION ORDER BY CreatedOn DESC
并按 = 1
过滤 .. 但我坚持加入。
注意:如果对软件特定关键字有任何疑问,我使用的是 SQL Server 2012。
使用 Count() over(Partition by)
技巧来做到这一点。
Over
子句将帮助您找到每个 group(LogType)
的计数,然后如您提到的那样使用 row_number
window 函数找到每个组中的前 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
试试下面的代码:
select LogType, count(1) as 'Count', max(CreatedOn) as 'MostRecent'
from yourtablename
group by LogType
order by Count desc
我正在尝试为我的结果集中的每个分组行获取前 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
(这很容易),但我不确定如何获取最新的然后 link 返回到以前的结果。我在考虑 ROW_NUMBER() / PARTITION ORDER BY CreatedOn DESC
并按 = 1
过滤 .. 但我坚持加入。
注意:如果对软件特定关键字有任何疑问,我使用的是 SQL Server 2012。
使用 Count() over(Partition by)
技巧来做到这一点。
Over
子句将帮助您找到每个 group(LogType)
的计数,然后如您提到的那样使用 row_number
window 函数找到每个组中的前 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
试试下面的代码:
select LogType, count(1) as 'Count', max(CreatedOn) as 'MostRecent'
from yourtablename
group by LogType
order by Count desc