问题
Example data:
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
Expected output:
Name | max_Domain1| max_Count1 | max_Domain2 | max_Count2 | datetime
--------------------------------------------------------------------------
John | google | 10 | apple | 8 | 2019-07-09
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'
回答1:
You need to partition by only year,month and day not the whole datetime:
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
回答2:
You seem to want the largest count per day:
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
回答3:
Try the following:
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
Example here
来源:https://stackoverflow.com/questions/57059966/top-2-max-value-excluding-duplicate-values