我正在尝试获取用户的排名的二维参数:donation sum
和total donor count
。
我的等级公式为:rank of [rank of donation_sum + rank of donor_count / 2]
样本表:
donation_id | user_id | donor_id | donation_sum
-----------------------------------------------
1 | 1 | 1 | 10
2 | 1 | 2 | 5
3 | 2 | 3 | 10
4 | 3 | 1 | 50
...
如您所见,有些捐赠者向不同的用户捐款,因此我使用sum(donation_sum)
和count(distinct(donation_id))
来获得准确的排名
我能够通过捐赠金额和捐赠总数分别获得2个sql的排名列表,但我需要的是在postgreSQL v.9.4中给定user_id
以上公式的用户等级
你有任何解决方案吗?所以我将在Yii2 PHP框架中使用该sql查询
由于
编辑: 我们将donation_date添加到tbl_donation并修改了实际查询,如下所示:
with list as (
select
s.runner_id, sum, count, rank_sum, rank_count,
(rank_sum+ rank_count)::float/ 2 as rank_avg,
row_number() over (order by rank_sum) as rank
from (
select *, rank() over (order by sum desc) rank_sum
from (
select runner_id, sum(donation_sum)
from tbl_donation
where donation_date >= '2015-01-01'
group by 1
) s
) s
join (
select *, rank() over (order by count desc) rank_count
from (
select runner_id, count(distinct(donator_id))
from tbl_donation
where donation_date >= '2015-01-01'
group by 1
) c
) c
using (runner_id)
)
select rank
from list
where runner_id = 251;
答案 0 :(得分:0)
在不同的子查询中进行两次排名:
select
s.user_id, sum, count, rank_sum, rank_count,
(rank_sum+ rank_count)::float/ 2 as rank_avg,
row_number() over (order by rank_sum) as rank
from (
select *, rank() over (order by sum desc) rank_sum
from (
select user_id, sum(donation_sum)
from donations
group by 1
) s
) s
join (
select *, rank() over (order by count desc) rank_count
from (
select user_id, count(distinct(donation_id))
from donations
group by 1
) c
) c
using (user_id);
user_id | sum | count | rank_sum | rank_count | rank_avg | rank
---------+-----+-------+----------+------------+----------+------
3 | 100 | 1 | 1 | 2 | 1.5 | 1
1 | 30 | 2 | 2 | 1 | 1.5 | 2
2 | 20 | 1 | 3 | 2 | 2.5 | 3
(3 rows)
如果您想为单rank
次使用user_id
选择with query
,例如:
with list as (
-- place here the above query
)
select rank
from list
where user_id = 2;