I would like to extract some data from three tables in a SQL Server 2005 database. While this can surely be done in code, it seems like this could be done reasonably well in SQL (bonus points for LINQ!).
Basically, I would like to know for each month how many calls and meetings each employee has held with each of our clients. Something like this:
Employee GUID Customer GUID Jan calls Jan mtgs Feb calls Feb mtgs...
[a guid] [another guid] 5 0 7 3
The data is spread across three tables. For simplicity's sake, let's just show the relevant columns:
Communications Table
[CommunicationId] (PK, uniqueidentifier)
[Type] (nvarchar(1)) ('C' for call, 'M' for meeting, etc.)
[Date] (datetime)
Person-Communication Table
[PersonId] (PK, FK, uniqueidentifier) (Can contain GUIDs for employees or clients, see Person Table below)
[CommunicationId] (PK, FK, uniqueidentifier)
Person Table
[PersonId] (PK, uniqueidentifier)
[Type] (nvarchar(1)) ('E' for employee, 'C' for customer)
So, the questions:
- Can this be done in SQL without horrendous code or big performance problems?
- If so, how? I'd even settle for a good high-level strategy. I'm guessing pivots will play a big role here (particularly the "Complex PIVOT Example"). DATEPART(MONTH, Date) seems like a good method for partitioning the communications by month along the lines of:
SELECT DATEPART(MONTH, Date), COUNT(*) FROM [CommunicationTable] WHERE DATEPART(YEAR, Date) = '2009' GROUP BY DATEPART(MONTH, Date) ORDER BY DATEPART(MONTH, Date)
... which gets me the number of communications in each month in 2009:
1 2871
2 2639
3 3654
4 2751
5 1773
6 2575
7 2906
8 2398
9 2621
10 2638
11 1705
12 2290