Vince Plaza's Blog

...Microsoft .NET programming ideas and samples

August 25th, 2009

...now browsing by day

 

Working with additive values in tables with different levels of detail

Tuesday, August 25th, 2009

Downloads: Sample Database

There are times when you need to perform a calculation on values stored in two different tables. The first value is stored in a summary level table, and the second is stored in a detail table. I will use the Adventure Works employee tables to demonstrate.

Let’s say you need to calculate the accrued vacation time for your employees that exceeds the company limit of 120 hours and derive the total liability to the company in terms of dollars. Using the Adventure Works database, that would require three tables: HumanResources.Employee, Person.Contact, and HumanResources.EmployeePayHistory. To start, we know we need to identify the employee so we include the EmployeeId field from the Employee table and the LastName and FirstName fields from the Contact table. Make sure and include the schema when declaring the tables, as this is required for any schema that is not ‘dbo’. This is a good practice anyway. Also, note the use of the table aliases ‘e’ and ‘c’ to save typing and add clarity.

select      e.EmployeeId
            ,c.LastName + ', ' + c.FirstName as EmployeeName
from        HumanResources.Employee e
inner join  Person.Contact c on e.ContactId = c.ContactId

Click to continue »