Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

sql - Calculating Running Total with OVER Clause and PARTITION BY Clause with counter

how to calculate the sum of points each week_number and user_name using a counter ? I use sum() OVER (PARTITION BY ORDER BY )

And I would like to have the maximum sum at 10.
How can I do this?

Here is my original table:

enter image description here

Here is the result I would like to obtain:

enter image description here

Here is the sql code:

SELECT week_number,
user_name,
sum(points) OVER (PARTITION BY user_name ORDER BY week_number) AS total_prime
FROM team;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this

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

I don't get it in your second table where alan have point 4 but have sum 2.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...