使用OVER子句和PARTITION BY子句与计数器计算运行总计

时间:2018-08-29 17:55:04

标签: sql postgresql sum window-functions

如何使用计数器计算每个week_number和user_name的积分总和? 我使用sum() OVER (PARTITION BY ORDER BY )

我希望最大金额为10。
我该怎么办?

这是我的原始桌子:

enter image description here

这是我想要获得的结果:

enter image description here

这是sql代码:

SELECT week_number,
user_name,
sum(points) OVER (PARTITION BY user_name ORDER BY week_number) AS total_prime
FROM team;

1 个答案:

答案 0 :(得分:2)

尝试一下

select 
  week_number, 
  user_name, 
  points, 
  case when total_prime > 10 then 10 else total_prime end as sum, 
  case when total_prime > 1 and total_prime < 10 then null 
       when total_prime > 10 then total_prime - 10 end as dif
from
  (select 
     week_number, 
     user_name, points, 
     sum(points) over (partition by user_name order by week_number) as total_prime 
   from 
     team) a

我没有在您的第二张表中找到该表,其中alanpoint 4但有sum 2