示例数据:
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个最大值相同。
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'
答案 0 :(得分:0)
您只需要按年,月和日进行分区,而不要按整个日期时间进行分区:
with main as
(
select name,domain,count,datetime
,row_number() over (partition by
name,domain,count,year(datetime)*10000+month(datetime)*100+day(datetime) order by
datetime desc) as row_number
from table
)
select *
from main
where row_number = 1
答案 1 :(得分:0)
尝试以下操作:
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
示例here
答案 2 :(得分:0)
您似乎想要每天最多的计数:
select t.*
from (select t.*,
row_number() over (partition by name, date(datetime) order by count desc) as seqnum
from tab t
where datetime >= '2019-07-08' and
datetime < '2019-07-10'
) t
where t.seqnum = 1
order by count desc