Note that there are some explanatory texts on larger screens.

plurals
  1. POCount entries across three tables based on month in SQL or LINQ
    primarykey
    data
    text
    <p>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!).</p> <p>Basically, I would like to know <strong>for each month how many calls and meetings each employee has held with each of our clients</strong>. Something like this:</p> <pre><code>Employee GUID Customer GUID Jan calls Jan mtgs Feb calls Feb mtgs... [a guid] [another guid] 5 0 7 3 </code></pre> <p>The data is spread across three tables. For simplicity's sake, let's just show the relevant columns:</p> <p><strong>Communications Table</strong></p> <pre><code>[CommunicationId] (PK, uniqueidentifier) [Type] (nvarchar(1)) ('C' for call, 'M' for meeting, etc.) [Date] (datetime) </code></pre> <p><strong>Person-Communication Table</strong></p> <pre><code>[PersonId] (PK, FK, uniqueidentifier) (Can contain GUIDs for employees or clients, see Person Table below) [CommunicationId] (PK, FK, uniqueidentifier) </code></pre> <p><strong>Person Table</strong></p> <pre><code>[PersonId] (PK, uniqueidentifier) [Type] (nvarchar(1)) ('E' for employee, 'C' for customer) </code></pre> <p>So, <strong>the questions</strong>:</p> <ol> <li>Can this be done in SQL without horrendous code or big performance problems?</li> <li>If so, how? I'd even settle for a good high-level strategy. I'm guessing <a href="http://msdn.microsoft.com/en-us/library/ms177410.aspx" rel="nofollow noreferrer">pivots</a> will play a big role here (particularly the "Complex PIVOT Example"). <a href="http://msdn.microsoft.com/en-us/library/ms174420.aspx" rel="nofollow noreferrer">DATEPART(MONTH, Date)</a> seems like a good method for partitioning the communications by month along the lines of:</li> </ol> <blockquote> <pre><code>SELECT DATEPART(MONTH, Date), COUNT(*) FROM [CommunicationTable] WHERE DATEPART(YEAR, Date) = '2009' GROUP BY DATEPART(MONTH, Date) ORDER BY DATEPART(MONTH, Date) </code></pre> </blockquote> <p>... which gets me the number of communications in each month in 2009:</p> <pre><code>1 2871 2 2639 3 3654 4 2751 5 1773 6 2575 7 2906 8 2398 9 2621 10 2638 11 1705 12 2290 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload