本文介绍了前 2 个最大值,不包括重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例数据:
Name | Domain | Count | datetime
----------------------------------------------------
John | google | 5 | 2019-07-09 01:00:01
John | apple | 6 | 2019-07-09 01:02:01
John | apple | 8 | 2019-07-09 01:03:01
John | google | 10 | 2019-07-09 01:11:01
John | dos | 1 | 2019-07-09 01:11:01
John | dos | 3 | 2019-07-09 01:11:01
预期输出:
Name | max_Domain1| max_Count1 | max_Domain2 | max_Count2 | datetime
--------------------------------------------------------------------------
John | google | 10 | apple | 8 | 2019-07-09
我尝试在分区上使用 row_number(),但它给我的日期值与前 2 个最大值相同.
I tried using row_number() over the partition, but it is giving me the same date values as top 2 maximum.
select t.*,
row_number() over (partition by name, date(datetime) order by count desc) as seqnum
from table t
where datetime >= '2019-07-08' and
datetime < '2019-07-09'
推荐答案
试试以下:
select name, domain, count, CONVERT(varchar(10),datetime, 126) as datetime
from
(
select top 2 t.*
from tab t
where datetime >= CONVERT(datetime,'2019-07-08', 101) and
datetime < CONVERT(datetime,'2019-07-10', 101)
order by row_number() over (partition by name, domain, cast(datetime as date) order by count desc) asc, count desc
) as t2
order by t2.datetime asc
示例这里
这篇关于前 2 个最大值,不包括重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!