Calculate Sum of Products Over Time With Changes in Historical Values - sql

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.

Related

SQL QUERY: Sum of amounts equal to last day of reporting month & cutoff date is equal to and greater than reporting month

I am trying to ask this question as best as i can so please forgive me inadvance if its not 100% clear.
I have a set of data which shows the date a transaction is processed.
For the same set of data I have the date of cut-off
what i am trying to achieve is finding the sum of transactions where:
Processed in a given month but the cut-off date is on the last day of the reporting month or future dated
e.g.
From the above on May-22 should have 100 and Jun-22 i should have 200 that has not met the original deadline.
Any help on this would be great. I have tried a few solutions but could not make them work

SQL - SUM two columns with a date range on one of the columns

First off its been a long week and I'm having a moment e.g. I just can't figure this out but I know its straight forward.
I have a CTE with a query for a GL Detail and one for Budget which are bought together to display all the details needed for a report.
For example the GL detail bring back the actual amount from a date range such as 2019-01-01 and 2019-04-01
and the budget part brings back the budget for each month so the date range is 2019-01-01 and 2019-12-01 as I need to sum up the total budget in a report.
Using an iif expression in SSRS the report shows the actuals up to the month a user select (there is on a to_date parameter)such as April then the report shows actual from Jan and then budget from May to Dec. I need to show the total of budget for the 12 month which is straight forward as I have bought each month amount back.
My question is I need to sum the GL actual amount for the months selected in by the user Jan to April and the remaining budget amounts May to Dec. For some reason I just can't work it out in my head.
Edit - I'm using
postgresql
SSRS - Microsoft SQL Server Reporting Services
columns are in GL is gldetail.amount and for Budget budget.amount_budget - I have a column in both gldetail and budget queries which is called post_date.
Worked it out -
,case
when src.post_date <= src._to_date then src.amount
when src.post_date > src._to_date then src.amount_budget
end as actual_budget_total
Then in the report sum the actual_budget_total

Power BI - Difference between amount per day and total in a table

I have a table with the sales from last 2 years, and I want to compare the sales from this year with the same natural day last year. For example, Sunday 1st of April 2018 will be compared with Sunday 2nd April 2017.
In order to do that I have created the measure
sales_last_year = CALCULATE(Sales[Revenue]); SAMEPERIODLASTYEAR(DATEADD('Calendar'[Date];+1;DAY)))
And I have created another measure where I have the value from the same day last year:
Prueba_sales_last_year = CALCULATE(Sales[Revenue]); SAMEPERIODLASTYEAR('Calendar'[Date]))
The result is the following:
Sales last year
As you can see the sales per day shows 5.316€ and 3.546€, which is correct, but the total is 111.796 €, which is not correct. However, the measure with the formula without the natural day the sum of the two rows is correct. How could I solve this?
Thank you very much in advance
I just changed the order to calculate the date and it was solved.
sales_last_year = CALCULATE(Sales[Revenue]);DATEADD( SAMEPERIODLASTYEAR('Calendar'[Date]);+1;DAY))

How do I summarise month to date forecast for current month in Power Pivot?

I have a table in a data model that has forecast figures for the next 3 months. What I want to do is to show what the forecast number for the current month to date is.
When I use the DATESMTD function like this:
=CALCULATE(SUM(InternetSales_USD[SalesAmount_USD]),DATESMTD(DateTime[DateKey]))
I get the last month of my data summarised as a total. I assume that is because the DATESMTD function takes the last date in the column and that is 3 months away.
How do I make sure I get this current month MTD total rather then the end of the calendar? The formula should be clever enough to realise I am in May and want the May MTD not the August MTD.
Any ideas?
The way to do this is to do this:
Forecast_Transaction_MTD:=CALCULATE(sum('ATO Online'[2017 Transaction Forecast]), DATESINPERIOD('ATO Online'[Current Year],TODAY(),-day(TODAY()),day))
the last -day(TODAY()) gets the day number for the current day and subtract it from today's date. So, today is the 25 May. the -day(TODAY())),day)) extracts the day (25) and subtracts it from the current date to get me to the 1 May.
The rest of the formula just adds the total for the dates.

T-SQL absence by month from start date end date

I have an interesting query to do and am trying to find the best way to do it. Basically I have an absence table in our personnel database this records the staff id and then a start date and end date for the absence. End date being null if not yet entered (not returned). I cannot change the design.
They would like a report by month on number of absences (12 month trend). With staff being off over the month change it obviously may be difficult to calculate.
e.g. Staff off 25/11/08 to 05/12/08 (dd/MM/yy) I would want the days in November to go into the November count and the ones in December in the December count.
I am currently thinking in order to count the number of days I need to separate the start and end date into a record for each day of the absence, assigning it to the month it is in. then group the data for reporting. As for the ones without an end date I would assume null is the current date as they are presently still absent.
What would be the best way to do this?
Any better ways?
Edit: This is SQL 2000 server currently. Hoping for an upgrade soon.
I have had a similar issue where there has been a table of start/end dates designed for data storage but not for reporting.
I sought out the "fastest executing" solution and found that it was to create a 2nd table with the monthly values in there. I populated it with the months from Jan 2000 to Jan 2070. I'm expecting it will suffice or that I get a large pay cheque in 2070 to come and update it...
DECLARE TABLE months (start DATETIME)
-- Populate with all month start dates that may ever be needed
-- And I would recommend indexing / primary keying by start
SELECT
months.start,
data.id,
SUM(CASE WHEN data.start < months.start
THEN DATEDIFF(DAY, months.start, data.end)
ELSE DATEDIFF(DAY, data.start, DATEADD(month, 1, months.start))
END) AS days
FROM
data
INNER JOIN
months
ON data.start < DATEADD(month, 1, months.start)
AND data.end > months.start
GROUP BY
months.start,
data.id
That join can be quite slow for various reasons, I'll search out another answer to another question to show why and how to optimise the join.
EDIT:
Here is another answer relating to overlapping date ranges and how to speed up the joins...
Query max number of simultaneous events