Top 2 max value excluding duplicate values

2019-07-25 09:58发布

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'

标签: sql database db2
3条回答
Melony?
2楼-- · 2019-07-25 10:16

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

查看更多
霸刀☆藐视天下
3楼-- · 2019-07-25 10:34

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
查看更多
狗以群分
4楼-- · 2019-07-25 10:40

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
查看更多
登录 后发表回答