使用 window 函数创建的列上的 MIN() MAX()
MIN() MAX() on a column created using window function
我使用 window 函数创建了一个名为 custom_rank 的列。有没有办法为每个用户标识获取该特定列的最小值和最大值?我基本上是在尝试根据给定用户的注册期限获得最小和最大重量。
select top 1000
c.weight, c.units,
rank() over (partition by uuid, enrolled_on order by enrolled_on desc, input_date asc) as "weight_rank"
from tableA a
join tableB b
on (b.member_no = a.member_no)
join tableC c
on (c.userId = b.uuid)
where input_date >= enrolled_on and input_date < cancel_date
使用 CTE,然后获取每个用户的 max/min。
with mm as
(
select top 1000
c.weight, c.units, c.userId
rank() over (partition by uuid, enrolled_on order by enrolled_on desc, input_date asc) as "weight_rank"
from tableA a
join tableB b
on (b.member_no = a.member_no)
join tableC c
on (c.userId = b.uuid)
where input_date >= enrolled_on and input_date < cancel_date
)
select userId, min(weight_rank), max(weight_rank)
from mm
group by userId;
只需使用 max()
和 min()
作为 window 函数:
with cte as (
select c.weight, c.units, uuid,
rank() over (partition by uuid, enrolled_on
order by enrolled_on desc, input_date asc) as weight_rank
from tableA a join
tableB b
on b.member_no = a.member_no join
tableC c
on c.userId = b.uuid
where input_date >= enrolled_on and input_date < cancel_date
)
select top 1000 cte.*,
max(weighted_rank) over (partition by uuid) as max_weightedrank_user,
min(weighted_rank) over (partition by uuid) as min_weightedrank_user,
from cte;
我使用 window 函数创建了一个名为 custom_rank 的列。有没有办法为每个用户标识获取该特定列的最小值和最大值?我基本上是在尝试根据给定用户的注册期限获得最小和最大重量。
select top 1000
c.weight, c.units,
rank() over (partition by uuid, enrolled_on order by enrolled_on desc, input_date asc) as "weight_rank"
from tableA a
join tableB b
on (b.member_no = a.member_no)
join tableC c
on (c.userId = b.uuid)
where input_date >= enrolled_on and input_date < cancel_date
使用 CTE,然后获取每个用户的 max/min。
with mm as
(
select top 1000
c.weight, c.units, c.userId
rank() over (partition by uuid, enrolled_on order by enrolled_on desc, input_date asc) as "weight_rank"
from tableA a
join tableB b
on (b.member_no = a.member_no)
join tableC c
on (c.userId = b.uuid)
where input_date >= enrolled_on and input_date < cancel_date
)
select userId, min(weight_rank), max(weight_rank)
from mm
group by userId;
只需使用 max()
和 min()
作为 window 函数:
with cte as (
select c.weight, c.units, uuid,
rank() over (partition by uuid, enrolled_on
order by enrolled_on desc, input_date asc) as weight_rank
from tableA a join
tableB b
on b.member_no = a.member_no join
tableC c
on c.userId = b.uuid
where input_date >= enrolled_on and input_date < cancel_date
)
select top 1000 cte.*,
max(weighted_rank) over (partition by uuid) as max_weightedrank_user,
min(weighted_rank) over (partition by uuid) as min_weightedrank_user,
from cte;