I have the following information (return by view):
DateTime ItemID UserTyp Seconds
2012-01-01 10 S 12
2012-01-01 10 S 18
2012-01-01 11 S 22
2012-01-02 11 M 52
2012-01-02 10 S 120
2012-01-02 11 S NULL
2012-01-03 15 M 112
2012-01-03 12 S 182
2012-01-04 10 M NULL
What I need to done is to calculated the sum of all seconds by user types, but for five periods.
The periods are set in the following way:
- Get the first and the last date
- Divided all days on five
- The result of the division is the days that one period includes
Then for each period, depending on the DateTime and the UserType of the records, I should come up with this records:
Periods UserTypeS_SUM(Seconds) UserTypeM_SUM(Seconds)
1
2
3
4
5
Also, I should check if there is at least 5 records, before the division is make – if I have 4 for example, only one period will be used.
I know it does not look so different, I have started to make a solution using function, but it looks kinda ineffective to me. Are there some build-in functions that could do this easy?
EDIT: I am really sorry but I have forget to mention that the I should this in view or table-valued function. No store procedures are allowed in this case.
try this:
SQL fiddle demo