示例数据:
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)
您似乎想要条件聚合:
select name,
max(case when seqnum = 1 then domain end) as domain_1,
max(case when seqnum = 1 then count end) as count_1,
max(case when seqnum = 2 then domain end) as domain_2,
max(case when seqnum = 2 then count end) as count_2,
date(datetime)
from (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'
) t
group by name, date(datetime);