I’m going to preface by saying that I’m fairly green with SQL.
My code below works, however I am missing two vital pieces of my employee population: (1) those employees who have been invoiced but had no corresponding payroll deduction, and (2) those employees who experienced payroll deductions but were not invoiced. The code, as it is now, only performs the arithmetic on employees who have corresponding data in both the Employee_Deductions and Employee_Invoices tables. I've been reading up on CASE, but am not certain if that's the path I should go down. I greatly appreciate any constructive critiques and suggestions on how to arrive at my desired result. Thank you.
SELECT
PayrollpersonID,
PayrollDeductionYear,
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December,
Total
FROM
(SELECT
PayrollpersonID,
PayrollDeductionAmount-i.invoice as Variance,
PayrollDeductionMonth,
PayrollDeductionYear,
Total = sum(PayrollDeductionAmount -i.invoice) over (partition by PayrollpersonID)
FROM
Employee_Deductions as d,
(SELECT
InvoicepersonID,
sum(isnull(v.InvoiceAmount,0.00)) as invoice,
InvoiceProcessedMonth,
InvoiceProcessedYear
FROM
Employee_Invoices as v
WHERE InvoiceProcessedYear = '2015'
GROUP BY InvoicepersonID, InvoiceProcessedMonth, InvoiceProcessedYear) as i
WHERE
d.PayrollpersonID = i.InvoicepersonID and
d.PayrollDeductionMonth = i.InvoiceProcessedMonth and
d.PayrollDeductionYear = i.InvoiceProcessedYear and
d.PayrollDeductionYear = '2015' and
d.PayrollDeductionAmount > 0)
SOURCE PIVOT
(
SUM(Variance) FOR PayrollDeductionMonth in (January, February, March, April, May, June,
July, August, September, October, November, December)
)
AS pivottable
ORDER BY PayrollpersonID;
Table Schema:
The [Employee_Deductions] table has the following columns:
PayrollDeductionYear nvarchar,
PayrollDeductionMonth nvarchar,
PayrollpersonID nvarchar,
LastName nvarchar,
FirstName nvarchar,
PayrollDeductionAmount money
The [Employee_Invoices] table has the following columns:
InvoiceProcessedYear nvarchar,
InvoiceProcessedMonth nvarchar,
InvoicepersonID nvarchar,
EmployeeLastName nvarchar,
EmployeeFirstName nvarchar,
EmployeeEmail nvarchar,
OrganizationID nvarchar,
OrgName nvarchar,
OrgAddress1 nvarchar,
OrgAddress2 nvarchar,
OrgCity nvarchar,
OrgState nvarchar,
OrgZip nvarchar,
OrgEIN nvarchar,
InvoiceAmount money
Result Table: