Single SQL Server query to get the total score by hourly, daily, weekly, monthly, and annual - sql

I have the following requirement :
single SQL Server query to get the total score by hourly, daily, weekly, monthly, and annual data.
this is how the result should be:
thisperiodtotalscore previousperiodtotalscore sumtotalscore periodType
which meets the following criteria:
where score comes from the table data, totalscore has to be summed up for the different members of different teams,
where period can be hourly, daily, weekly, monthly, and annual and hourly is determined by the working hour definition, say it can be any number of selected hours (example: 1st working hour, 2nd working hour, and so on..)
and weekly determined by working days definition, say it can be wednesday to wednesday,..)
and likewise for monthy and annual
If the period has empty data, say if it is a holiday/leave that particular period should not be skipped in the count.
Note:
thisperiodtotalscore (this period total score can be for any of the periods (hourly, daily, weekly, monthly, annual) for the user date input) - say the corresponding week score of the user input, the corresponding month score of the user date input, .. likewise
previousperiodtotalscore (previous period total score can be for any of the periods (hourly, daily, weekly, monthly, annual) for the user date input) - say previous week score of the user date input, previous month score of the user date input,.. likewise
sumtotalscore - total of the thisperiodtotalscore and previousperiodtotalscore
periodType - hourly, daily, weekly, monthly, annual, based on the period request type
and which meets the following criteria:
where score comes from the table data, totalscore has to be summed up for the different members of different teams,
where period can be hourly, daily, weekly, monthly, and annual
and hourly is determined by the working hour definition, say it can be any number of selected hours (example: 1st working hour, 2nd working hour, and so on..)
and weekly determined by working days definition, say it can be wednesday to wednesday,..)
and likewise for monthly and annual
If the period has empty data, say if it is a holiday/leave that particular period should not be skipped in the count.
This is the requirement, also Welcome for other possible cases if missed in such kind of scenarios.
Thanks in advance,
GravityPush

For start, take a look at DimDate in AdventureWorksDW sample. You can have a similar table in your database and write some join queries. I suggest use queries which are dynamically grouped by different columns of DimDate.

Related

Ms ACCESS: calculating past annual averages over varying date ranges

In a form on Ms ACCESS, a user can select a commodity (such as copper, nickel, etc.) from a list and a commodity price date from a list. A trailing 12 month average commodity price should then be calculated.
For example: the user selects Copper as commodity and February 1st 2010, 02/01/2010. I then want the average price to be calculated over the time period: [02/01/2009 - 02/01/2010].
I'm not sure how to write this in query form. This is the current incomplete code;
SELECT Avg(CommPrices.Price) AS Expr1,
FROM CommPrices
WHERE (((CommPrices.Commodity)=[Forms]![Tool Should Cost]![List243]))
AND CommPrices.DateComm = [Forms]![Tool Should Cost]![List55];
List243 is the list of commodities the user can select from, list55 is the list of dates the user can select. All data is obtained from the table CommPrices.
Note: the earliest dates in the column DateComm is 01/01/2008. So if the user selects a date for example 02/01/2008, then calculating the average over the past 12 months before 02/01/2008 won't be possible. I do want the code to still calculate the average using the dates available. (in the example it would just be the average over the past month)
Second Note: the column DateComm only has monthly dates for the first day of every month (e.g 01/01/2008, 02/01/2008, 03/01/2008). The dates listed in list55 can refer to different days in the month (e.g 03/16/2009), in that case I want the code to still calculate the past 12 month average using the closest commodity dates possible. So if the user selects date 03/16/2009, I want the code to calculate the 12 month average for 03/01/2008 - 03/01/2009.
For "integer" months it would be:
SELECT
Avg(CommPrices.Price) AS AveragePrice,
FROM
CommPrices
WHERE
CommPrices.Commodity=[Forms]![Tool Should Cost]![List243]
AND
CommPrices.DateComm = BETWEEN
DateSerial(Year([Forms]![Tool Should Cost]![List55]) - 1, Month([Forms]![Tool Should Cost]![List55]), 1)
AND
DateSerial(Year([Forms]![Tool Should Cost]![List55]), Month([Forms]![Tool Should Cost]![List55]), 1)

SQL Statement to return previous quarter balance

I'm trying to create a query that can return the previous quarter balance for a series of records.
I have financial data for accountid (acctid), fiscal year (fyear), fiscal quarter (fquarter) and fiscal period (fperiod) that I'm summing and tracking through a series of other queries that I'm dropping in to a temporary table, that data includes the net change for the period (nperiod), net change for the quarter (nquarter) and net change for the year (nyear). Net change for the period is only the account transactions in the period, net change for the quarter is the cumulative total of the transactions that appear in periods 1-3, 4-6, 7-9 and 10-12 respectively (amount from previous periods are not calculated in proceeding quarters, ie the net change for the quarter resets to $0 for periods 4, 7 and 9) and the net change for the year is the total cumulative sum. I'm now trying to create a sql statement that returns the previous quarter end balance.
So for periods 1-3 I need to write a separate select statements to return the ending balance for the previous year, for periods 4-6 I want them ALL to return the net change for the quarter from period 3, for 7-9 I want to return the net change for the quarter from period 6 for all records and for period 10-12 I want to return net change for the quarter from period 9.
Can I get some assistance because I have a gigantic query that returns the max period per quarter, then the nquarter amount associated with that period and then trying to do a where exists, but something tells me there's a better way to do it.
Thanks!

Excel MDX - same period last month - totals

I have the following MDX expression which helps me to display the data for the 'same period last month' from the Cube PER DAY.
Filter(
[Date].[Date].[Date],
[Date].[Date].CurrentMember.Member_Value >=
DateSerial(Year(DateAdd('m', -1, VBA![Date]())),
Month(DateAdd('m', -1, VBA![Date]())),
1
)
AND [Date].[Date].CurrentMember.Member_Value < DateAdd('m', -1, VBA![Date]())
)
Now I would like to redo the code to display just the total for this period without breaking it down per day. The reason for this is, that if for example I want to see the total number of active users for the same period last month I can't simply sum up the numbers of daily users as this will be higher than the real number of total users in this period (user may be active on more than one day and I just want to count him once for this period).
I tried chaning the code but nothing works so far. Any ideas?
Many thanks in advance,
Maciej

How to query for grouped results in Access, based on count of time and day of week?

I have a table in an Access 2013 database, which has many rows of incidents, each of which has a "time" column and a "day_of_week" column. I need to query for a result set that shows a count of incidents during hourly time ranges from 6:00am-5:00pm, per day of the week. I can get a total count of incidents per time range like so:
SELECT "6:00AM - 6:59AM" AS [Time Range],COUNT(time) AS [Count]
FROM Incidents
WHERE time >= #6:00:00 AM# AND time <=#6:59:00 AM#
UNION
SELECT "7:00AM - 7:59AM" AS [Time Range],COUNT(time) AS [Count]
FROM Incidents
WHERE time >= #7:00:00 AM# AND time <=#7:59:00 AM#
UNION
...
So on, and so forth. It is a lengthy query, but it gets the task done. However, as stated previously, I need to drill down further to figure out how many incidents occurred specifically during each hourly time frame, per day of the week. So, I need to have a column for "time", and then an additional column for each day of the week. I know this will involve some grouping, but I am not certain what must be done.
This is my first post here. Hopefully I followed the rules.
Thanks
This query should do what you need, except that it will only show hour as an hour number, rather than the expanded description your query fragment above shows:
select day_of_week, datepart("h",[time]) as hour_num, count(*)
from incidents
group by day_of_week, datepart("h",[time])
hope this helps

Calculate Sum of Products Over Time With Changes in Historical Values

Given two (simplified) tables in Access 2010:
**tblDailyLabour**
DailyLabourID - PK
DateRecorded
EmployeeID
QtyHours
**tblEmployeeHistory**
EmpHistoryID - PK
DateApplicable
EmployeeID
PayRate
Employee1 is entered into the database today. He's set in an 'Address Book' of employees with various values assigned to him. As of today he has a PayRate of $23.50/hr.
So from today moving forward, all hours logged will be calculated against today's rate for Employee1 at (23.50 * [QtyHours])
A month goes by and Employee1 gets a wage increase to $25.00/hr. This value is logged as a new entry in the 'Employee History' and is active as of, say, April 17th. So from April 17th onward he is now being calculated at (25.00 * [QtyHours]).
On a daily report this is straight forward as a query checks the report date and calculates the totals for Employee1. Whether the report is March 17th or April 25th, the query looks up the assigned rate and figures the total cost.
However, if I were to create an administrative report that was to evaluate the total cost of all days between March 17th and June 3rd, there may be several changes in the employee rates that need to be accounted for.
This is where I'm having a problem. I can't figure out how to not show any previous rates if DateApplicable is <= DateRecorded.
How might I go about writing a query that determines the rate on each day - dependent on the value in the Employee History - and calculate a total sum?
I apologize in advance if this question isn't phrased very well, but thanks a heap for any help!
I think it might be easier if you did a date range (start date & end date) in the 'address book' instead of just the start date.
On the current record, make the end date 12/31/9999. When entering a new current record, update the end date of the last record.