-1

Using SQL I have a list of credits for a course by year. I want to get a count of how many values the 'credits' attribute has been over years. If a value occurs twice (non consecutively) I want it counted. As follows, you can see there are 3 distinct values for CREDITS (5, 7.5, 6.5) over the timeframe but if credits have been values (5, 7.5, 6.5 and then back to 5) over the years, I want 4 as the result.

Dataset and desired result

Dense rank is not working and does not give me what I want as just gives me distinct values in the timeframe, rather than 4 (non distinct) values across the timeframe given, with respect to time. Is this doable in SQL?

Jojo
  • 13
  • 2
  • Please can you edit your question and add the simple data/expected out as text not images, so it can be easy for us to help you, also tag the database you are using – SelVazi May 25 '23 at 09:13
  • Also can you share the query that you have tried ? – SelVazi May 25 '23 at 09:14

1 Answers1

1

You can use a running sum with a case expression that checks if the credits value has been changed:

select year_, credits,
  sum(case when credits<>pre_credits then 1 else 0 end)
  over (order by year_ desc) + 1 res_rnk
from
(
  select *,
    lag(credits, 1, credits) over (order by year_ desc) pre_credits
  from tbl
) t
order by year_ desc

demo

ahmed
  • 9,071
  • 3
  • 9
  • 22
  • 1
    Ahmed, thanks SO MUCH for answering my first SQL post. Appreciate your time, you have made my day. Works beautifully. – Jojo May 25 '23 at 10:08