DominionZA
Executive Member
- Joined
- May 5, 2005
- Messages
- 8,309
I use window functions quite extensively and have finally gotten myself into a hole.
Consider the following expression...
AvgOutgoingMass = AVG(sr_Hoppers.Mass) OVER (PARTITION BY sr_Levels.Shaft_Id, sr_Hoppers.Alias ORDER BY sr_Trains.EventDateTime, sr_Hoppers.N1 ROWS BETWEEN 10 PRECEDING AND 1 PRECEDING)
has the range fixed at the previous 10 records. I need to make this dynamic as each of our clients needs to be able to set how many they want to use to work out the average.
The solutions I have come up with - which are not options really...
1. Dynamic SQL. Firstly - yuk. Secondly - the query is rather large. Just don't like dynamic SQL if I can help it.
2. CASE statements where for each potential option (1, 2, 3, ...) your statement defines the entire window function with each specific n PRECEDING. Also no go as this value can be whatever the client wishes - no cap.
We are targeting SQL 2014, with a minimum requirement of SQL 2012.
Pity variables are not supported as that would just make my life simple.
Any ideas from the SQL gurus?
Consider the following expression...
AvgOutgoingMass = AVG(sr_Hoppers.Mass) OVER (PARTITION BY sr_Levels.Shaft_Id, sr_Hoppers.Alias ORDER BY sr_Trains.EventDateTime, sr_Hoppers.N1 ROWS BETWEEN 10 PRECEDING AND 1 PRECEDING)
has the range fixed at the previous 10 records. I need to make this dynamic as each of our clients needs to be able to set how many they want to use to work out the average.
The solutions I have come up with - which are not options really...
1. Dynamic SQL. Firstly - yuk. Secondly - the query is rather large. Just don't like dynamic SQL if I can help it.
2. CASE statements where for each potential option (1, 2, 3, ...) your statement defines the entire window function with each specific n PRECEDING. Also no go as this value can be whatever the client wishes - no cap.
We are targeting SQL 2014, with a minimum requirement of SQL 2012.
Pity variables are not supported as that would just make my life simple.
Any ideas from the SQL gurus?