I have a view that I want to use to generate a payroll report.
I want it such that it selects/gets the last 3 months of monthly processed data.
E.g. If today is 15th May 2012 and payroll for May has not been done, I want to get the results for April, March and February only.
My query:
SELECT dbo.[@EIM_PROCESS_DATA].U_Tax_year, dbo.[@EIM_PROCESS_DATA].U_Employee_ID, SUM(dbo.[@EIM_PROCESS_DATA].U_Amount) AS PAYE,
dbo.OADM.CompnyName, dbo.OADM.CompnyAddr, dbo.OADM.TaxIdNum, dbo.OHEM.lastName + ', ' + ISNULL(dbo.OHEM.middleName, '')
+ ' ' + ISNULL(dbo.OHEM.firstName, '') AS EmployeeName, dbo.OHEM.govID, dbo.[@EIM_PROCESS_DATA].U_Process_month
FROM dbo.[@EIM_PROCESS_DATA] INNER JOIN
dbo.OHEM ON dbo.[@EIM_PROCESS_DATA].U_Employee_ID = dbo.OHEM.empID CROSS JOIN
dbo.OADM
WHERE (dbo.[@EIM_PROCESS_DATA].U_PD_code = 'SYS033')
GROUP BY dbo.[@EIM_PROCESS_DATA].U_Tax_year, dbo.[@EIM_PROCESS_DATA].U_Employee_ID, dbo.OADM.CompnyName, dbo.OADM.CompnyAddr, dbo.OADM.TaxIdNum,
dbo.OHEM.lastName, dbo.OHEM.firstName, dbo.OHEM.middleName, dbo.OHEM.govID, dbo.[@EIM_PROCESS_DATA].U_Process_month
The field U_Process_Month stores the name of the months of the year (varchar). Any help?
Here is one option if you want to turn a month name into a datetime:
Replace the @Month and @Year variables with your field names, and you have the first step 😉
For selecting only the last three months, try the
HAVINGclause, together with a variable@MaxKeydatethat indicates the last processed month:You need to see yourself, if you can determine the value for
@MaxKeyDatewith a simpleor if it is more complicated.