对于每种方式,我需要为每个用户(user_id)计算3个最大值。
我的表:
> db=# SELECT * FROM test;
id | user_id | value | way
----+------------+----------+------
1 | 1 | 10 | 1
2 | 2 | 30 | 1
3 | 3 | 20 | 1
4 | 1 | 50 | 2
5 | 2 | 40 | 2
6 | 3 | 60 | 2
7 | 2 | 70 | 3
8 | 4 | 5 | 1
(8 rows)
我需要的表格:
user_id | MAX1 | MAX2 | MAX3
----+------------+----------+------
1 | 0 | 1 | 1
2 | 2 | 0 | 1
3 | 1 | 1 | 0
4 | 1 | 0 | 0
我。即 user_id 2 在方式1,方式3 上具有最大值,在方式3 上具有最大值。 user_id 1 在方式2 上排名第二,在方式1 排名第三。 等
请帮我创建正确的查询。
谢谢!
答案 0 :(得分:1)
您需要在row_number partitioned by way order by value
;
cte
with cte as(
select
id,
user_id,val,
row_number() over(partition by way order by val desc) rank,
val,
way
from test)
select distinct cte2.user_id,
(select count(*) from cte where cte.rank=1 and cte.user_id=cte2.user_id) as MAX1,
(select count(*) from cte where cte.rank=2 and cte.user_id=cte2.user_id) as MAX2,
(select count(*) from cte where cte.rank=3 and cte.user_id=cte2.user_id) as MAX3
from cte cte2 where rank<=3
order by 1
答案 1 :(得分:0)
我最接近理解这个问题的是它只是条件聚合:
select user_id,
sum(case when way = 1 then 1 else 0 end) as way1,
sum(case when way = 2 then 1 else 0 end) as way2,
sum(case when way = 3 then 1 else 0 end) as way3
from test
group by user_id;
我注意到您的原始数据有8行,结果集中的数字加起来为8.我不知道&#34; max&#34;是为了。