<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Program With Dave &#187; SQL</title>
	<atom:link href="http://www.daveandrews.org/category/sql/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.daveandrews.org</link>
	<description>My Programming Tutorials and Experiments</description>
	<lastBuildDate>Thu, 29 Jul 2010 06:00:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Difference Between Union and Union All</title>
		<link>http://www.daveandrews.org/2010/07/29/difference-between-union-and-union-all/</link>
		<comments>http://www.daveandrews.org/2010/07/29/difference-between-union-and-union-all/#comments</comments>
		<pubDate>Thu, 29 Jul 2010 06:00:51 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=381</guid>
		<description><![CDATA[Sometimes it can be confusing what the difference between &#8216;union&#8217; in a SQL statement and &#8216;union all&#8217; means. The basic definition is that &#8216;union&#8217; will combine a given set (query results) with the values of a second set that don&#8217;t already exist. &#8216;Union All&#8217; will simply append the second set to the end of the [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes it can be confusing what the difference between &#8216;union&#8217; in a SQL statement and &#8216;union all&#8217; means. The basic definition is that &#8216;union&#8217; will combine a given set (query results) with the values of a second set that don&#8217;t already exist. &#8216;Union All&#8217; will simply append the second set to the end of the first set, which includes all the records of the first set and all the records of the second set.</p>
<p>Let&#8217;s see an example.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #cc66cc;">1</span> MyValue
&nbsp;
<span style="color: #993333; font-weight: bold;">UNION</span>
&nbsp;
<span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #cc66cc;">1</span> MyValue</pre></td></tr></table></div>

<p>Here we are combining two sets of data which each contain a single record, 1. If you execute this command, you will get back a single row which contains the value 1 in the MyValue column. This is because the new value we union in already existed in the first data set, so it did not include it.</p>
<table border = 1 style="border-collapse:collapse">
<tr>
<th>MyValue</th>
</tr>
<tr>
<td>1</td>
</tr>
</table>
<p>Let&#8217;s modify our query to use Union All.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #cc66cc;">1</span> MyValue
&nbsp;
<span style="color: #993333; font-weight: bold;">UNION</span> <span style="color: #993333; font-weight: bold;">ALL</span>
&nbsp;
<span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #cc66cc;">1</span> MyValue</pre></td></tr></table></div>

<p>We now get back a set with two records, the 1 from the first set AND the 1 from the second set.</p>
<table border = 1 style="border-collapse:collapse">
<tr>
<th>MyValue</th>
</tr>
<tr>
<td>1</td>
</tr>
<tr>
<td>1</td>
</tr>
</table>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2010/07/29/difference-between-union-and-union-all/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Inserting Results of a Query into a Table</title>
		<link>http://www.daveandrews.org/2010/07/25/inserting-results-of-a-query-into-a-table/</link>
		<comments>http://www.daveandrews.org/2010/07/25/inserting-results-of-a-query-into-a-table/#comments</comments>
		<pubDate>Sun, 25 Jul 2010 06:00:42 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[Insert]]></category>
		<category><![CDATA[Select]]></category>
		<category><![CDATA[Tables]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=369</guid>
		<description><![CDATA[Sometimes its necessary to populate an existing table with the results of a query. This can be done very easily with an INSERT statement combined with a SELECT. A typical insert query looks like this. 1 2 3 4 5 6 7 8 9 10 INSERT INTO Person &#40;Name, Address, Phone &#41; VALUES &#40;'Test Guy', [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes its necessary to populate an existing table with the results of a query. This can be done very easily with an INSERT statement combined with a SELECT.</p>
<p>A typical insert query looks like this.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> Person 
     <span style="color: #66cc66;">&#40;</span>Name<span style="color: #66cc66;">,</span> 
      Address<span style="color: #66cc66;">,</span> 
      Phone
     <span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">VALUES</span> 
     <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'Test Guy'</span><span style="color: #66cc66;">,</span> 
      <span style="color: #ff0000;">'123 Test St'</span><span style="color: #66cc66;">,</span> 
      <span style="color: #ff0000;">'555-5555'</span>
     <span style="color: #66cc66;">&#41;</span></pre></td></tr></table></div>

<p>This works fine for just one row. But what if we had another table which contained the information we needed, and had 100000 rows that we wanted to copy over? Let&#8217;s just combine our INSERT with a SELECT!</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> Person 
     <span style="color: #66cc66;">&#40;</span>Name<span style="color: #66cc66;">,</span> 
      Address<span style="color: #66cc66;">,</span> 
      Phone
     <span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">SELECT</span>
     Name<span style="color: #66cc66;">,</span>
     Address<span style="color: #66cc66;">,</span>
     Phone
<span style="color: #993333; font-weight: bold;">FROM</span>
     TableThatHasValues</pre></td></tr></table></div>

<p>It&#8217;s that easy! The SELECT query will execute and the results of that select query will be piped into the INSERT command, inserting every single row.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2010/07/25/inserting-results-of-a-query-into-a-table/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Selecting data into a new table</title>
		<link>http://www.daveandrews.org/2010/07/23/selecting-data-into-a-new-table/</link>
		<comments>http://www.daveandrews.org/2010/07/23/selecting-data-into-a-new-table/#comments</comments>
		<pubDate>Fri, 23 Jul 2010 06:00:49 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[Select Queries]]></category>
		<category><![CDATA[Temp Tables]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=367</guid>
		<description><![CDATA[If you have a series of data that you want to insert into a new table, or into a temporary table, it&#8217;s very simple. This can be used to create a simple backup of records, or to take a very long and complex query and save its results for future use. If you save into [...]]]></description>
			<content:encoded><![CDATA[<p>If you have a series of data that you want to insert into a new table, or into a temporary table, it&#8217;s very simple. This can be used to create a simple backup of records, or to take a very long and complex query and save its results for future use. If you save into a table, that table won&#8217;t have any relationships that are in the existing table, just something to keep in mind.</p>
<p>Let&#8217;s say we have a query like this.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span>
     <span style="color: #66cc66;">*</span>
<span style="color: #993333; font-weight: bold;">FROM</span>
     Animals a
     <span style="color: #993333; font-weight: bold;">INNER</span> <span style="color: #993333; font-weight: bold;">JOIN</span> Animal_Details ad
          <span style="color: #993333; font-weight: bold;">ON</span> a<span style="color: #66cc66;">.</span>AnimalID <span style="color: #66cc66;">=</span> ad<span style="color: #66cc66;">.</span>AnimalID</pre></td></tr></table></div>

<p>This table will join together two tables and pull in the details of whatever animals are in the animals table. I just made this up quickly. Let&#8217;s have SQL save that to a new table.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span>
     <span style="color: #66cc66;">*</span>
<span style="color: #993333; font-weight: bold;">INTO</span> 
     AnimalDetailsCombined
<span style="color: #993333; font-weight: bold;">FROM</span>
     Animals a
     <span style="color: #993333; font-weight: bold;">INNER</span> <span style="color: #993333; font-weight: bold;">JOIN</span> Animal_Details ad
          <span style="color: #993333; font-weight: bold;">ON</span> a<span style="color: #66cc66;">.</span>AnimalID <span style="color: #66cc66;">=</span> ad<span style="color: #66cc66;">.</span>AnimalID</pre></td></tr></table></div>

<p>This query will create a brand new table called AnimalDetailsCombined and save the results of that query into the table. If you wanted to save to a temporary table, which would be deleted once the connection is closed, just add a hashtag (#) in front of the table name.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span>
     <span style="color: #66cc66;">*</span>
<span style="color: #993333; font-weight: bold;">INTO</span> 
     <span style="color: #808080; font-style: italic;">#AnimalDetailsCombined</span>
<span style="color: #993333; font-weight: bold;">FROM</span>
     Animals a
     <span style="color: #993333; font-weight: bold;">INNER</span> <span style="color: #993333; font-weight: bold;">JOIN</span> Animal_Details ad
          <span style="color: #993333; font-weight: bold;">ON</span> a<span style="color: #66cc66;">.</span>AnimalID <span style="color: #66cc66;">=</span> ad<span style="color: #66cc66;">.</span>AnimalID</pre></td></tr></table></div>

<p>You now have a temporary table called #AnimalDetailsCombined with is the result of the query.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2010/07/23/selecting-data-into-a-new-table/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using SQL To Accrue Values (Overtime in Time Entries)</title>
		<link>http://www.daveandrews.org/2010/03/15/using-sql-to-accrue-values-overtime-in-time-entries/</link>
		<comments>http://www.daveandrews.org/2010/03/15/using-sql-to-accrue-values-overtime-in-time-entries/#comments</comments>
		<pubDate>Tue, 16 Mar 2010 03:37:43 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=313</guid>
		<description><![CDATA[I&#8217;ve made it an exercise recently to write SQL code that will determine overtime hours and regular hours given a list of time entries. I wanted to do this through a single (well, nested) SQL query and to not use cursors to iterate through the entries. The problem is that we have a table of [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve made it an exercise recently to write SQL code that will determine overtime hours and regular hours given a list of time entries. I wanted to do this through a single (well, nested) SQL query and to not use cursors to iterate through the entries.</p>
<p>The problem is that we have a table of time entries, the date the entries were made, and the employee who made them and we need to accrue the hours that employee worked in a given week. This is simple to do with iterators in code or cursors in T-SQL, but what fun would that be?</p>
<p>I&#8217;m going to simplify the problem by only looking at a single week of data. In a larger solution which looks over a larger range of dates such as a month you will need a subquery which assigns each week a number and group by that week number. In my full blown implementation of this, I used row_number() over (order by startdate) given a list of weeks with a startdate and enddate. But that is for a later post.</p>
<p>Let&#8217;s look at our week&#8217;s worth of data, which has 2 employees.</p>
<p><strong>Table TimeEntries</strong></p>
<table style="border-collapse: collapse;" border="1">
<tbody>
<tr>
<th>TimeEntryID</th>
<th>EmployeeID</th>
<th>DateWorked</th>
<th>Hours</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>2010-01-04</td>
<td>8</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>2010-01-05</td>
<td>10</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>2010-01-06</td>
<td>7.5</td>
</tr>
<tr>
<td>4</td>
<td>1</td>
<td>2010-01-07</td>
<td>10</td>
</tr>
<tr>
<td>5</td>
<td>1</td>
<td>2010-01-08</td>
<td>10</td>
</tr>
<tr>
<td>6</td>
<td>1</td>
<td>2010-01-09</td>
<td>4</td>
</tr>
<tr>
<td>7</td>
<td>2</td>
<td>2010-01-04</td>
<td>10</td>
</tr>
<tr>
<td>8</td>
<td>2</td>
<td>2010-01-05</td>
<td>10</td>
</tr>
<tr>
<td>9</td>
<td>2</td>
<td>2010-01-06</td>
<td>10</td>
</tr>
<tr>
<td>10</td>
<td>2</td>
<td>2010-01-07</td>
<td>10</td>
</tr>
</tbody>
</table>
<p>As you can infer from the above, employee 1 worked overtime (more than 40 hours) starting on the 8th, and employee 2 worked no overtime, since the employee worked exactly 40 hours in that week.</p>
<p><strong>Problem 1: Multiple Records in a Day</strong> The first problem we must overcome is calculating the total number of hours worked in a given day. This is because we can have an employee who puts in 4 hours in the morning and 4 hours in the afternoon. If we don&#8217;t have this in a single record, it will be difficult down the line when our complicated joins and subqueries come in.</p>
<p>So we build this query which will sum up the hours in a given day. We will use this in a couple of places.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span>
	te<span style="color: #66cc66;">.</span>EmployeeId<span style="color: #66cc66;">,</span>
	te<span style="color: #66cc66;">.</span>DateWorked<span style="color: #66cc66;">,</span>
	SUM<span style="color: #66cc66;">&#40;</span>te<span style="color: #66cc66;">.</span>Hours<span style="color: #66cc66;">&#41;</span> TotalHoursInDay
<span style="color: #993333; font-weight: bold;">FROM</span>
	TimeEntries te
<span style="color: #993333; font-weight: bold;">GROUP</span> <span style="color: #993333; font-weight: bold;">BY</span>
	te<span style="color: #66cc66;">.</span>EmployeeId<span style="color: #66cc66;">,</span>
	te<span style="color: #66cc66;">.</span>DateWorked</pre></td></tr></table></div>

<p>Very simple, we&#8217;re just summing up the hours per day. We&#8217;re going to use this query in several places.</p>
<p><strong>Problem 2: Finding out which days are in overtime.</strong> The next thing we need to overcome is to come up with a means of determining which days should be in overtime. This is where &#8220;accrual&#8221; of sorts comes into play. We join each day&#8217;s record to every record before it. We then group that record and sum up the hours previous to the given day.</p>
<p>Let&#8217;s look at the query.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span>
	te<span style="color: #66cc66;">.</span>EmployeeId<span style="color: #66cc66;">,</span>
	te<span style="color: #66cc66;">.</span>TotalHoursInDay<span style="color: #66cc66;">,</span>
	te<span style="color: #66cc66;">.</span>DateWorked<span style="color: #66cc66;">,</span>
	sum<span style="color: #66cc66;">&#40;</span>previous<span style="color: #66cc66;">.</span>TotalHoursInDay<span style="color: #66cc66;">&#41;</span> HoursUpToThisPoint<span style="color: #66cc66;">,</span>
	case when te<span style="color: #66cc66;">.</span>TotalHoursInDay <span style="color: #66cc66;">+</span> SUM<span style="color: #66cc66;">&#40;</span>previous<span style="color: #66cc66;">.</span>TotalHoursInDay<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&gt;</span> <span style="color: #cc66cc;">40</span> then <span style="color: #ff0000;">'Y'</span>
		 else <span style="color: #ff0000;">'N'</span>
	end InOvertime
<span style="color: #993333; font-weight: bold;">FROM</span>
	<span style="color: #66cc66;">&#40;</span>
		<span style="color: #993333; font-weight: bold;">SELECT</span>
			te<span style="color: #66cc66;">.</span>EmployeeId<span style="color: #66cc66;">,</span>
			te<span style="color: #66cc66;">.</span>DateWorked<span style="color: #66cc66;">,</span>
			SUM<span style="color: #66cc66;">&#40;</span>te<span style="color: #66cc66;">.</span>Hours<span style="color: #66cc66;">&#41;</span> TotalHoursInDay
		<span style="color: #993333; font-weight: bold;">FROM</span>
			TimeEntries te
		<span style="color: #993333; font-weight: bold;">GROUP</span> <span style="color: #993333; font-weight: bold;">BY</span>
			te<span style="color: #66cc66;">.</span>EmployeeId<span style="color: #66cc66;">,</span>
			te<span style="color: #66cc66;">.</span>DateWorked
	<span style="color: #66cc66;">&#41;</span> te
	<span style="color: #993333; font-weight: bold;">LEFT</span> <span style="color: #993333; font-weight: bold;">JOIN</span>
	<span style="color: #66cc66;">&#40;</span>
		<span style="color: #993333; font-weight: bold;">SELECT</span>
			te<span style="color: #66cc66;">.</span>EmployeeId<span style="color: #66cc66;">,</span>
			te<span style="color: #66cc66;">.</span>DateWorked<span style="color: #66cc66;">,</span>
			SUM<span style="color: #66cc66;">&#40;</span>te<span style="color: #66cc66;">.</span>Hours<span style="color: #66cc66;">&#41;</span> TotalHoursInDay
		<span style="color: #993333; font-weight: bold;">FROM</span>
			TimeEntries te
		<span style="color: #993333; font-weight: bold;">GROUP</span> <span style="color: #993333; font-weight: bold;">BY</span>
			te<span style="color: #66cc66;">.</span>EmployeeId<span style="color: #66cc66;">,</span>
			te<span style="color: #66cc66;">.</span>DateWorked
	<span style="color: #66cc66;">&#41;</span> previous
		<span style="color: #993333; font-weight: bold;">ON</span>	te<span style="color: #66cc66;">.</span>EmployeeId <span style="color: #66cc66;">=</span> previous<span style="color: #66cc66;">.</span>EmployeeId <span style="color: #993333; font-weight: bold;">AND</span>
			te<span style="color: #66cc66;">.</span>DateWorked <span style="color: #66cc66;">&gt;</span> previous<span style="color: #66cc66;">.</span>DateWorked
<span style="color: #993333; font-weight: bold;">GROUP</span> <span style="color: #993333; font-weight: bold;">BY</span>
	te<span style="color: #66cc66;">.</span>EmployeeId<span style="color: #66cc66;">,</span>
	te<span style="color: #66cc66;">.</span>TotalHoursInDay<span style="color: #66cc66;">,</span>
	te<span style="color: #66cc66;">.</span>DateWorked</pre></td></tr></table></div>

<p>The first subquery, te, creates a list of each day for each employee and the total hours for that day. This is to get the total current hours for the employee for the given day. We join that to the second subquery, previous. The Previous query generates a total number for all days PRIOR to the given day. (The logic comes from our join condition, te.DateWorked > previous.DateWorked)</p>
<p>The InOvertime flag will be used later on to determine overtime hours. It lets us know when the employee has crossed the threshold. That could probably be taken out, but it simplifies the logic later on.</p>
<p>So we get these results:</p>
<table style="border-collapse: collapse;" border="1" cellspacing="4" cellpadding="4">
<tbody>
<tr>
<th>EmployeeID</th>
<th>TotalHoursInDay</th>
<th>DateWorked</th>
<th>HoursUpToThisPoint</th>
<th>InOvertime</th>
</tr>
<tr>
<td>1</td>
<td>8</td>
<td>2010-01-04</td>
<td>NULL</td>
<td>N</td>
</tr>
<tr>
<td>1</td>
<td>10</td>
<td>2010-01-05</td>
<td>8</td>
<td>N</td>
</tr>
<tr>
<td>1</td>
<td>7.5</td>
<td>2010-01-06</td>
<td>18</td>
<td>N</td>
</tr>
<tr>
<td>1</td>
<td>10</td>
<td>2010-01-07</td>
<td>25.5</td>
<td>N</td>
</tr>
<tr>
<td>1</td>
<td>10</td>
<td>2010-01-08</td>
<td>35.5</td>
<td>Y</td>
</tr>
<tr>
<td>1</td>
<td>4</td>
<td>2010-01-08</td>
<td>45.5</td>
<td>Y</td>
</tr>
<tr>
<td>2</td>
<td>10</td>
<td>2010-01-04</td>
<td>NULL</td>
<td>N</td>
</tr>
<tr>
<td>2</td>
<td>10</td>
<td>2010-01-05</td>
<td>10</td>
<td>N</td>
</tr>
<tr>
<td>2</td>
<td>10</td>
<td>2010-01-06</td>
<td>20</td>
<td>N</td>
</tr>
<tr>
<td>2</td>
<td>10</td>
<td>2010-01-07</td>
<td>30</td>
<td>N</td>
</tr>
</tbody>
</table>
<p>As you can see, this subquery determines for us the total number of hours up until the given day, and when combined with the hours worked in the given day we know if the employee is in overtime or not.</p>
<p>Let&#8217;s put one more wrapper around this which will total up the hours and tell us how many hours were regular hours and how many were overtime.</p>
<p>Here is our final query.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span>
	EmployeeId<span style="color: #66cc66;">,</span>
	sum<span style="color: #66cc66;">&#40;</span>case when InOvertime <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'N'</span> then TotalHoursInDay
	         when InOvertime <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'Y'</span> <span style="color: #993333; font-weight: bold;">AND</span> HoursUpToThisPoint <span style="color: #66cc66;">&lt;</span> <span style="color: #cc66cc;">40</span> then  <span style="color: #cc66cc;">40</span> <span style="color: #66cc66;">-</span> HoursUpToThisPoint
		 else <span style="color: #cc66cc;">0</span>
	end<span style="color: #66cc66;">&#41;</span> RegularHours<span style="color: #66cc66;">,</span>
	sum<span style="color: #66cc66;">&#40;</span>case when InOvertime <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'Y'</span> then
		 case when HoursUpToThisPoint <span style="color: #66cc66;">&gt;</span> <span style="color: #cc66cc;">40</span> then TotalHoursInDay
			  else HoursUpToThisPoint <span style="color: #66cc66;">+</span> TotalHoursInDay <span style="color: #66cc66;">-</span> <span style="color: #cc66cc;">40</span>
		 end
		 else <span style="color: #cc66cc;">0</span>
	end<span style="color: #66cc66;">&#41;</span> OTHours
<span style="color: #993333; font-weight: bold;">FROM</span>
<span style="color: #66cc66;">&#40;</span>
	<span style="color: #993333; font-weight: bold;">SELECT</span>
		te<span style="color: #66cc66;">.</span>EmployeeId<span style="color: #66cc66;">,</span>
		te<span style="color: #66cc66;">.</span>TotalHoursInDay<span style="color: #66cc66;">,</span>
		te<span style="color: #66cc66;">.</span>DateWorked<span style="color: #66cc66;">,</span>
		sum<span style="color: #66cc66;">&#40;</span>previous<span style="color: #66cc66;">.</span>TotalHoursInDay<span style="color: #66cc66;">&#41;</span> HoursUpToThisPoint<span style="color: #66cc66;">,</span>
		case when te<span style="color: #66cc66;">.</span>TotalHoursInDay <span style="color: #66cc66;">+</span> SUM<span style="color: #66cc66;">&#40;</span>previous<span style="color: #66cc66;">.</span>TotalHoursInDay<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&gt;</span> <span style="color: #cc66cc;">40</span> then <span style="color: #ff0000;">'Y'</span>
			 else <span style="color: #ff0000;">'N'</span>
		end InOvertime
	<span style="color: #993333; font-weight: bold;">FROM</span>
		<span style="color: #66cc66;">&#40;</span>
			<span style="color: #993333; font-weight: bold;">SELECT</span>
				te<span style="color: #66cc66;">.</span>EmployeeId<span style="color: #66cc66;">,</span>
				te<span style="color: #66cc66;">.</span>DateWorked<span style="color: #66cc66;">,</span>
				SUM<span style="color: #66cc66;">&#40;</span>te<span style="color: #66cc66;">.</span>Hours<span style="color: #66cc66;">&#41;</span> TotalHoursInDay
			<span style="color: #993333; font-weight: bold;">FROM</span>
				TimeEntries te
			<span style="color: #993333; font-weight: bold;">GROUP</span> <span style="color: #993333; font-weight: bold;">BY</span>
				te<span style="color: #66cc66;">.</span>EmployeeId<span style="color: #66cc66;">,</span>
				te<span style="color: #66cc66;">.</span>DateWorked
		<span style="color: #66cc66;">&#41;</span> te
		<span style="color: #993333; font-weight: bold;">LEFT</span> <span style="color: #993333; font-weight: bold;">JOIN</span>
		<span style="color: #66cc66;">&#40;</span>
			<span style="color: #993333; font-weight: bold;">SELECT</span>
				te<span style="color: #66cc66;">.</span>EmployeeId<span style="color: #66cc66;">,</span>
				te<span style="color: #66cc66;">.</span>DateWorked<span style="color: #66cc66;">,</span>
				SUM<span style="color: #66cc66;">&#40;</span>te<span style="color: #66cc66;">.</span>Hours<span style="color: #66cc66;">&#41;</span> TotalHoursInDay
			<span style="color: #993333; font-weight: bold;">FROM</span>
				TimeEntries te
			<span style="color: #993333; font-weight: bold;">GROUP</span> <span style="color: #993333; font-weight: bold;">BY</span>
				te<span style="color: #66cc66;">.</span>EmployeeId<span style="color: #66cc66;">,</span>
				te<span style="color: #66cc66;">.</span>DateWorked
		<span style="color: #66cc66;">&#41;</span> previous
			<span style="color: #993333; font-weight: bold;">ON</span>	te<span style="color: #66cc66;">.</span>EmployeeId <span style="color: #66cc66;">=</span> previous<span style="color: #66cc66;">.</span>EmployeeId <span style="color: #993333; font-weight: bold;">AND</span>
				te<span style="color: #66cc66;">.</span>DateWorked <span style="color: #66cc66;">&gt;</span> previous<span style="color: #66cc66;">.</span>DateWorked
	<span style="color: #993333; font-weight: bold;">GROUP</span> <span style="color: #993333; font-weight: bold;">BY</span>
		te<span style="color: #66cc66;">.</span>EmployeeId<span style="color: #66cc66;">,</span>
		te<span style="color: #66cc66;">.</span>TotalHoursInDay<span style="color: #66cc66;">,</span>
		te<span style="color: #66cc66;">.</span>DateWorked
<span style="color: #66cc66;">&#41;</span> HoursQuery
<span style="color: #993333; font-weight: bold;">GROUP</span> <span style="color: #993333; font-weight: bold;">BY</span>
	HoursQuery<span style="color: #66cc66;">.</span>EmployeeId</pre></td></tr></table></div>

<table style="border-collapse: collapse;" border="1" cellspacing="4" cellpadding="4">
<tr>
<th>EmployeeId</th>
<th>RegularHours</th>
<th>OTHours</th>
</tr>
<tr>
<td>1</td>
<td>40</td>
<td>9.5</td>
</tr>
<tr>
<td>2</td>
<td>40</td>
<td>0</td>
</tr>
</table>
<p>What we have done here is add some logic that acts on whether or not the a given time entry is in overtime. We group by the employee so we can aggregate hours.</p>
<p>If the record is in overtime, it might mean the employee is already over 40 hours or it might mean that the current record puts the employee over 40 hours. So we have to add a check that will take the difference as regular hours, since the hours that take the employee up to 40 are still regular hours.</p>
<p>The second check is to calculate overtime. If the time entry puts the employee over 40, then take the amount over 40 as overtime. If the employee is already over 40, then the entire entry is overtime.</p>
<p>I hope this post helps you have the mindset of doing as much as possible with your queries, rather than writing code to calculate values which can easily be queried.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2010/03/15/using-sql-to-accrue-values-overtime-in-time-entries/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Using COALESCE() in Linq-To-SQL</title>
		<link>http://www.daveandrews.org/2009/11/23/using-coalesce-in-linq-to-sql/</link>
		<comments>http://www.daveandrews.org/2009/11/23/using-coalesce-in-linq-to-sql/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 16:52:05 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[CSharp]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=270</guid>
		<description><![CDATA[I had a situation today where I wanted to return a user&#8217;s name using Linq. Sure, I could have easily written some code for this, but for the sake of keeping my code simple and readable I wanted Linq to handle the building of the name. Users Table UserID FirstName LastName 1 David Andrews 2 [...]]]></description>
			<content:encoded><![CDATA[<p>I had a situation today where I wanted to return a user&#8217;s name using Linq. Sure, I could have easily written some code for this, but for the sake of keeping my code simple and readable I wanted Linq to handle the building of the name.</p>
<p><strong>Users Table</strong></p>
<table cellpadding = 5 cellspacing = 2 border = 1 style = "border-collapse:collapse">
<tr>
<th>UserID</th>
<th>FirstName</th>
<th>LastName</th>
</tr>
<tr>
<td>1</td>
<td>David</td>
<td>Andrews</td>
</tr>
<tr>
<td>2</td>
<td>Bob</td>
<td><i>NULL</i></td>
</tr>
</table>
<p>The Linq seemed easy:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">string</span> GetNameOfUser<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> userID<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            DatabaseDataContext dc <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DatabaseDataContext<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            var user <span style="color: #008000;">=</span> from u <span style="color: #0600FF;">in</span> dc.<span style="color: #0000FF;">Users</span>
                       where u.<span style="color: #0000FF;">UserID</span> <span style="color: #008000;">==</span> userID
                       select u.<span style="color: #0000FF;">FirstName</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span> <span style="color: #008000;">+</span> u.<span style="color: #0000FF;">LastName</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span>user.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">?</span> <span style="color: #666666;">&quot;Unknown User&quot;</span> <span style="color: #008000;">:</span> user.<span style="color: #0000FF;">First</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>However my results were not correct. Bob was left out because he did not have a last name value (it&#8217;s NULL in the database.) You will get results like this if you run that for each user (one at a time, but I put them in a table here.)</p>
<p><strong>Results</strong></p>
<table cellpadding = 5 cellspacing = 2 border = 1 style = "border-collapse:collapse">
<tr>
<th>Expected</th>
<th>Value Received</th>
</tr>
<tr>
<td>David Andrews</td>
<td>David Andrews</td>
</tr>
<tr>
<td>Bob</td>
<td><i>&lt;Empty String&gt;</i></td>
</tr>
</table>
<p>In SQL it is very common to use the COALESCE() function to handle problems with null values. But how can I do that in Linq? I didn&#8217;t want to write extra code to check for nulls and concatenate the values myself.</p>
<p>The answer is simple: <b>??</b>.  Yes, that&#8217;s right. Two question marks is the &#8220;coalesce&#8221; operator in Linq. It&#8217;s a good idea to wrap what you are testing in coalesce inside parenthesis as well.</p>
<p>What follows is my new function.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">string</span> GetNameOfUser<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> userID<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            DatabaseDataContext dc <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DatabaseDataContext<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            var user <span style="color: #008000;">=</span> from u <span style="color: #0600FF;">in</span> dc.<span style="color: #0000FF;">Users</span>
                       where u.<span style="color: #0000FF;">UserID</span> <span style="color: #008000;">==</span> userID
                       select <span style="color: #000000;">&#40;</span>u.<span style="color: #0000FF;">FirstName</span> <span style="color: #008000;">??</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span> <span style="color: #008000;">+</span> <span style="color: #000000;">&#40;</span>u.<span style="color: #0000FF;">LastName</span> <span style="color: #008000;">??</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span>user.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">?</span> <span style="color: #666666;">&quot;Unknown User&quot;</span> <span style="color: #008000;">:</span> user.<span style="color: #0000FF;">First</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>As you can see, I&#8217;ve added ?? &#8220;&#8221; after both FirstName and LastName. This translates to:</p>
<p>coalesce(FirstName, &#8221;)<br />
coalesce(LastName, &#8221;)</p>
<p>Which means that if FirstName is null you will get &#8221;, which adds correctly in SQL to another string. Same goes for LastName.</p>
<p>Here are my new results:</p>
<p><strong>Results</strong></p>
<table cellpadding = 5 cellspacing = 2 border = 1 style = "border-collapse:collapse">
<tr>
<th>Expected</th>
<th>Value Received</th>
</tr>
<tr>
<td>David Andrews</td>
<td>David Andrews</td>
</tr>
<tr>
<td>Bob</td>
<td>Bob</td>
</tr>
</table>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2009/11/23/using-coalesce-in-linq-to-sql/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Join on Multiple Columns in Linq To SQL</title>
		<link>http://www.daveandrews.org/2009/11/20/join-on-multiple-columns-in-linq-to-sql/</link>
		<comments>http://www.daveandrews.org/2009/11/20/join-on-multiple-columns-in-linq-to-sql/#comments</comments>
		<pubDate>Fri, 20 Nov 2009 16:57:03 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[CSharp]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=241</guid>
		<description><![CDATA[Today I had to create a Linq-To-SQL query which joined two tables. These tables had compound primary keys (table simplified for example): Table Referrers ServerID (PK) ReferrerID (PK) Value 1 1 My value 1 1 2 My value 2 1 3 My value 3 Table ReferrerInfo ServerID (PK) ReferrerID (PK) Value 1 1 More info&#8230; [...]]]></description>
			<content:encoded><![CDATA[<p>Today I had to create a Linq-To-SQL query which joined two tables. These tables had compound primary keys (table simplified for example):</p>
<p><strong>Table Referrers</strong></p>
<table cellpadding = 5 cellspacing = 2 border = 1 style = "border-collapse:collapse;">
<tr>
<th>ServerID (PK)</th>
<th>ReferrerID (PK)</th>
<th>Value</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>My value 1</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>My value 2</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
<td>My value 3</td>
</tr>
</table>
<p><strong>Table ReferrerInfo</strong></p>
<table cellpadding = 5 cellspacing = 2 border = 1 style = "border-collapse:collapse;">
<tr>
<th>ServerID (PK)</th>
<th>ReferrerID (PK)</th>
<th>Value</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>More info&#8230; 1</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>More info&#8230; 2</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
<td>More Info&#8230; 3</td>
</tr>
</table>
<p>So I wanted to join these together using a Linq-To-SQL query. The first thought that occured to me was to use a join:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">var referrers <span style="color: #008000;">=</span> from r <span style="color: #0600FF;">in</span> Referrers
               join ri <span style="color: #0600FF;">in</span> ReferrerInfo on r.<span style="color: #0000FF;">ServerConnectionID</span> equals ri.<span style="color: #0000FF;">ServerConnectionID</span> ..... <span style="color: #008000;">??????</span>
               select r<span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>So, apparently in C# you cannot do multiple columns in your join. I have to join on both ServerConnectionID and ReferrerID.</p>
<p>This page: <a href="http://www.onedotnetway.com/linq-to-sql-join-on-multiple-conditions/">http://www.onedotnetway.com/linq-to-sql-join-on-multiple-conditions/</a> explains one method to do so, but unfortunately that Linq query only works in VB.</p>
<p>So, I ended up writing a Linq-To-SQL that just uses the old style of joining, by using the where clause!</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">var referrers <span style="color: #008000;">=</span> from r <span style="color: #0600FF;">in</span> Referrers
                from ri <span style="color: #0600FF;">in</span> Referrer_Info
                where r.<span style="color: #0000FF;">ServerConnectionID</span> <span style="color: #008000;">==</span> ri.<span style="color: #0000FF;">ServerConnectionID</span> <span style="color: #008000;">&amp;&amp;</span>
                   r.<span style="color: #0000FF;">ReferrerID</span> <span style="color: #008000;">==</span> ri.<span style="color: #0000FF;">ReferrerID</span>
                select r<span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>This successfully executes my multi-column join.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2009/11/20/join-on-multiple-columns-in-linq-to-sql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Row_Number() to Enumerate and Partition Records in SQL Server</title>
		<link>http://www.daveandrews.org/2009/10/30/using-row_number-to-enumerate-and-partition-records-in-sql-server/</link>
		<comments>http://www.daveandrews.org/2009/10/30/using-row_number-to-enumerate-and-partition-records-in-sql-server/#comments</comments>
		<pubDate>Fri, 30 Oct 2009 11:25:15 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=171</guid>
		<description><![CDATA[I had a situation recently where I had a table full of people records, where the people were divided into families. The business logic that needed to be followed was that I had to assign a &#8220;Twin Code&#8221; to each record. This meant that for each family in the database, if two or more members [...]]]></description>
			<content:encoded><![CDATA[<p>I had a situation recently where I had a table full of people records, where the people were divided into families. The business logic that needed to be followed was that I had to assign a &#8220;Twin Code&#8221; to each record. This meant that for each family in the database, if two or more members were born on the same day they should be treated as twins. The twins should be assigned a number enumerating them in order of birth. If the member was not a twin, they should just receive the twin code of 1.</p>
<p>Here&#8217;s an example table:</p>
<table cellpadding = 5 cellspacing = 2 border = 1 style = "border-collapse:collapse;">
<tr>
<th>PersonID</th>
<th>FamilyID</th>
<th>FirstName</th>
<th>LastName</th>
<th>DateOfBirth</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>Joe</td>
<td>Johnson</td>
<td>2000-10-23 13:00:00</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>Jim</td>
<td>Johnson</td>
<td>2001-12-15 05:45:00</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>Karly</td>
<td>Matthews</td>
<td>2000-05-20 04:00:00</td>
</tr>
<tr>
<td>4</td>
<td>2</td>
<td>Kacy</td>
<td>Matthews</td>
<td>2000-05-20 04:02:00</td>
</tr>
<tr>
<td>5</td>
<td>2</td>
<td>Tom</td>
<td>Matthews</td>
<td>2001-09-15 11:52:00</td>
</tr>
</table>
<p>There are lots of ways to achieve the desired result, but the simplest is to just use a simple SELECT statement combined with the <b>ROW_NUMBER()</b> function with a couple parameters as to how to number the rows!</p>
<p>ROW_NUMBER() provides you with the number of a row in a given recordset, where you provide details on how to number the records. For example, if I just had to number the records above based solely upon the date of birth (ignoring families) then I would use this query:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span>
     <span style="color: #66cc66;">&#91;</span>PersonID<span style="color: #66cc66;">&#93;</span>
    <span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>FamilyID<span style="color: #66cc66;">&#93;</span>
    <span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>FirstName<span style="color: #66cc66;">&#93;</span>
    <span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>LastName<span style="color: #66cc66;">&#93;</span>
    <span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>DateOfBirth<span style="color: #66cc66;">&#93;</span>
    <span style="color: #66cc66;">,</span>ROW_NUMBER<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> over <span style="color: #66cc66;">&#40;</span><span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> DateOfBirth<span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">AS</span> Number
<span style="color: #993333; font-weight: bold;">FROM</span>
	People
<span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> 
	PersonID</pre></td></tr></table></div>

<p>This just tells the ROW_NUMBER() function to order its numbering ascending by DateOfBirth. Notice that I apply an order myself later on in the query, which is different than the row_number() order. I would get these results:</p>
<table cellpadding = 5 cellspacing = 2 border = 1 style = "border-collapse:collapse;">
<tr>
<th>PersonID</th>
<th>FamilyID</th>
<th>FirstName</th>
<th>LastName</th>
<th>DateOfBirth</th>
<th>Number</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>Joe</td>
<td>Johnson</td>
<td>2000-10-23 13:00:00</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>Jim</td>
<td>Johnson</td>
<td>2001-12-15 05:45:00</td>
<td>5</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>Karly</td>
<td>Matthews</td>
<td>2000-05-20 04:00:00</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>2</td>
<td>Kacy</td>
<td>Matthews</td>
<td>2000-05-20 04:02:00</td>
<td>2</td>
</tr>
<tr>
<td>5</td>
<td>2</td>
<td>Tom</td>
<td>Matthews</td>
<td>2001-09-15 11:52:00</td>
<td>4</td>
</tr>
</table>
<p>The number field that is assigned to each record is in the order of DateOfBirth.</p>
<p>Ordering my numbering by DateOfBirth is just half of the picture. I also need to &#8220;group&#8221; the records by the FamilyID. This is where a clause in T-SQL that you might not be very familiar with comes into play: &#8220;PARTITION BY&#8221;. The PARTITION BY clause allows us to group the results within the call to ROW_NUMBER() without grouping them ourselves via a GROUP BY. It just tells the ROW_NUMBER what groupings to use when it does its counting.</p>
<p>Here is our final SQL statement, which achieves the business logic we wanted to implement.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> 
       <span style="color: #66cc66;">&#91;</span>PersonID<span style="color: #66cc66;">&#93;</span>
      <span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>FamilyID<span style="color: #66cc66;">&#93;</span>
      <span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>FirstName<span style="color: #66cc66;">&#93;</span>
      <span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>LastName<span style="color: #66cc66;">&#93;</span>
      <span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>DateOfBirth<span style="color: #66cc66;">&#93;</span>
      <span style="color: #66cc66;">,</span>ROW_NUMBER<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> over<span style="color: #66cc66;">&#40;</span>PARTITION <span style="color: #993333; font-weight: bold;">BY</span> FamilyID<span style="color: #66cc66;">,</span> 
                         CONVERT<span style="color: #66cc66;">&#40;</span>NVARCHAR<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">25</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span> DateOfBirth<span style="color: #66cc66;">,</span> <span style="color: #cc66cc;">111</span><span style="color: #66cc66;">&#41;</span> 
                         <span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> DateOfBirth <span style="color: #993333; font-weight: bold;">ASC</span><span style="color: #66cc66;">&#41;</span> TwinCode
&nbsp;
  <span style="color: #993333; font-weight: bold;">FROM</span> <span style="color: #66cc66;">&#91;</span>People<span style="color: #66cc66;">&#93;</span>
<span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span>
	PersonID</pre></td></tr></table></div>

<p>In the ROW_NUMBER function above, I am doing several things. I&#8217;m grouping on FamilyID, and also grouping on a converted DateOfBirth. I convert the DateOfBirth to an nvarchar using the 111 conversion code, because that gets results like &#8217;2009/10/11&#8242; and &#8217;2009/10/12&#8242; which can easily be grouped by to achieve distinct dates. </p>
<p>Grouping on the Family, DateOfBirth, and then sorting by DateOfBirth ascending achieves the desired result for the ROW_NUMBER. Here are the results of the query:</p>
<table cellpadding = 5 cellspacing = 2 border = 1 style = "border-collapse:collapse;">
<tr>
<th>PersonID</th>
<th>FamilyID</th>
<th>FirstName</th>
<th>LastName</th>
<th>DateOfBirth</th>
<th>TwinCode</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>Joe</td>
<td>Johnson</td>
<td>2000-10-23 13:00:00</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>Jim</td>
<td>Johnson</td>
<td>2001-12-15 05:45:00</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>Karly</td>
<td>Matthews</td>
<td>2000-05-20 04:00:00</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>2</td>
<td>Kacy</td>
<td>Matthews</td>
<td>2000-05-20 04:02:00</td>
<td>2</td>
</tr>
<tr>
<td>5</td>
<td>2</td>
<td>Tom</td>
<td>Matthews</td>
<td>2001-09-15 11:52:00</td>
<td>1</td>
</tr>
</table>
<p>As you can see, the two people who qualify as twins above (Karly and Kacy) are enumerated correctly, with Karly receiving a 1 and Kacy receiving a 2. All the records that are not twins properly receive a 1.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2009/10/30/using-row_number-to-enumerate-and-partition-records-in-sql-server/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SQL Server &#8211; Using Computed or Calculated Columns in Tables</title>
		<link>http://www.daveandrews.org/2009/10/21/sql-server-using-computed-or-calculated-columns-in-tables/</link>
		<comments>http://www.daveandrews.org/2009/10/21/sql-server-using-computed-or-calculated-columns-in-tables/#comments</comments>
		<pubDate>Thu, 22 Oct 2009 02:34:11 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=160</guid>
		<description><![CDATA[You are probably used to writing views to access data in your tables when there is some sort of computation that must be made in a field. But did you know that you can have your tables make computations themselves, without running through a view? This can be done with Computed (or Calculated) Columns. These [...]]]></description>
			<content:encoded><![CDATA[<p>You are probably used to writing views to access data in your tables when there is some sort of computation that must be made in a field. But did you know that you can have your tables make computations themselves, without running through a view?</p>
<p>This can be done with <strong>Computed (or Calculated) Columns.</strong> These columns are table-level expressions that can operate on the other fields in a given record.</p>
<p>Let&#8217;s create a table which uses computed columns. I am going to create a table called Programmers which allows me to store a programmer&#8217;s first name, last name, middle initial, and date of birth. The table will include two computed columns: one which combines the elements of the name into a FullName field, and a second column which tells me the programmer&#8217;s age. This will all be achieved directly in the table, without the use of a view.</p>
<p>First, let&#8217;s create the table. Here is the query to create all of the fields except the computed ones.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span> Programmers
<span style="color: #66cc66;">&#40;</span>
	ProgrammerID INT IDENTITY<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">,</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
	FirstName NVARCHAR<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">30</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span>
	LastName NVARCHAR<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">30</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span>
	MiddleInit NCHAR<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span>
	DateOfBirth DATETIME<span style="color: #66cc66;">,</span></pre></td></tr></table></div>

<p>Now, let&#8217;s create our first computed column. The syntax is simple. Just begin with the name of the column, and then in parenthesis define the expression which will calculate the value of the column.</p>
<p>Let&#8217;s begin with the FullName calculation. Just add the LastName, a comma, FirstName, and MiddleInit, and then trim white space off the right to handle a missing initial.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;">        FullName <span style="color: #993333; font-weight: bold;">AS</span> <span style="color: #66cc66;">&#40;</span>rtrim<span style="color: #66cc66;">&#40;</span>coalesce<span style="color: #66cc66;">&#40;</span>LastName<span style="color: #66cc66;">,</span> <span style="color: #ff0000;">''</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">+</span> <span style="color: #ff0000;">', '</span> <span style="color: #66cc66;">+</span>
            coalesce<span style="color: #66cc66;">&#40;</span>FirstName<span style="color: #66cc66;">,</span> <span style="color: #ff0000;">''</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">+</span> <span style="color: #ff0000;">' '</span> <span style="color: #66cc66;">+</span> 
            coalesce<span style="color: #66cc66;">&#40;</span>MiddleInit<span style="color: #66cc66;">,</span> <span style="color: #ff0000;">''</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span></pre></td></tr></table></div>

<p>There we have it, our FullName calculation. Each field is encapsulated in coalesce to handle NULL values properly.</p>
<p>The last calculation will be the age. The age is simply the difference in years of the current date from the birth date.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;">	Age <span style="color: #993333; font-weight: bold;">AS</span> <span style="color: #66cc66;">&#40;</span>datediff<span style="color: #66cc66;">&#40;</span>year<span style="color: #66cc66;">,</span> DateOfBirth<span style="color: #66cc66;">,</span> getdate<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#41;</span></pre></td></tr></table></div>

<p>We also add a following parenthesis to close out our &#8220;CREATE TABLE&#8221; statement.</p>
<p>Now lets insert some test data. I added a few records with some NULLs for good testing measure. All standard stuff here. Notice we are not inserting the FullName or Age values.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> Programmers<span style="color: #66cc66;">&#40;</span>FirstName<span style="color: #66cc66;">,</span> LastName<span style="color: #66cc66;">,</span> MiddleInit<span style="color: #66cc66;">,</span> DateOfBirth<span style="color: #66cc66;">&#41;</span>
     <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'David'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'Andrews'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'C'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'1984-09-20'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> Programmers<span style="color: #66cc66;">&#40;</span>FirstName<span style="color: #66cc66;">,</span> LastName<span style="color: #66cc66;">,</span> MiddleInit<span style="color: #66cc66;">,</span> DateOfBirth<span style="color: #66cc66;">&#41;</span> 
     <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'Billy'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'Jenkins'</span><span style="color: #66cc66;">,</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'1990-01-20'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> Programmers<span style="color: #66cc66;">&#40;</span>FirstName<span style="color: #66cc66;">,</span> LastName<span style="color: #66cc66;">,</span> MiddleInit<span style="color: #66cc66;">,</span> DateOfBirth<span style="color: #66cc66;">&#41;</span> 
     <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'Robert'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'Anderson'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'K'</span><span style="color: #66cc66;">,</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">&#41;</span></pre></td></tr></table></div>

<p>Now lets test out our fields, using nothing more than a SELECT.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">*</span> <span style="color: #993333; font-weight: bold;">FROM</span> Programmers</pre></td></tr></table></div>

<p>We will get the following results:</p>
<table cellspacing = 2 cellpadding = 3 border = 1 style = 'border-collapse:collapse;'>
<tr>
<th>ProgrammerID</th>
<th>FirstName</th>
<th>LastName</th>
<th>MiddleInit</th>
<th>DateOfBirth</th>
<th>FullName</th>
<th>Age</th>
</tr>
<tr>
<td>1</td>
<td>David</td>
<td>Andrews</td>
<td>C</td>
<td>1984-09-20 00:00:00.000</td>
<td><strong>Andrews, David C</strong></td>
<td><strong>25</strong></td>
</tr>
<tr>
<td>2</td>
<td>Billy</td>
<td>Jenkins</td>
<td>NULL</td>
<td>1990-01-20 00:00:00.000</td>
<td><strong>Jenkins, Billy</strong></td>
<td><strong>19</strong></td>
</tr>
<tr>
<td>3</td>
<td>Robert</td>
<td>Anderson</td>
<td>K</td>
<td>NULL</td>
<td><strong>Anderson, Robert K</strong></td>
<td><strong>NULL</strong></td>
</tr>
</table>
<p>I emphasized the calculated fields above. Our query did not calculate them, they were considered to be just a part of the table since they are calculated fields.</p>
<p>One thing to keep in mind about calculated fields is that they are difficult to modify. You have to DROP the field and then ADD it back with the same name. This can change the order of fields in your query if you use SELECT *. It can also affect any triggers you may have which rely on the fields being in a certain order.</p>
<p>Also keep in mind any overhead that calculated fields may produce. It&#8217;s a good idea to use them for absolutely basic, atomic information, such as what I presented above. Complex calculations could become taxing to your queries.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2009/10/21/sql-server-using-computed-or-calculated-columns-in-tables/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Understanding SQL Joins &#8211; The Left Join</title>
		<link>http://www.daveandrews.org/2009/10/21/understanding-sql-joins-the-left-join/</link>
		<comments>http://www.daveandrews.org/2009/10/21/understanding-sql-joins-the-left-join/#comments</comments>
		<pubDate>Thu, 22 Oct 2009 00:40:02 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=151</guid>
		<description><![CDATA[SQL joins are a crucial part of anything more than the simplest of queries. Many programmers who do not fully comprehend SQL joins end up writing bloated software which will pull information from one table, store it, then run another query to get the information they want to join on. They then use code to [...]]]></description>
			<content:encoded><![CDATA[<p>SQL joins are a crucial part of anything more than the simplest of queries. Many programmers who do not fully comprehend SQL joins end up writing bloated software which will pull information from one table, store it, then run another query to get the information they want to join on. They then use code to process the join. It is much more efficient to have the SQL server handle the joining and processing of these records for you than to create custom code which ties tables together.</p>
<p>Let&#8217;s use these tables as an example.</p>
<p><strong>AnimalTypes table</strong></p>
<table style="border-collapse:collapse;" border="1" cellspacing="2" cellpadding="5">
<tbody>
<tr>
<th>AnimalTypeID</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>Dog</td>
</tr>
<tr>
<td>2</td>
<td>Cat</td>
</tr>
<tr>
<td>3</td>
<td>Turtle</td>
</tr>
<tr>
<td>4</td>
<td>Ferret</td>
</tr>
</tbody>
</table>
<p><strong>Animals table</strong></p>
<table style="border-collapse:collapse;" border="1" cellspacing="2" cellpadding="5">
<tbody>
<tr>
<th>AnimalID</th>
<th>AnimalTypeID</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>Dusty</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>Jonesey</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>Bonnie</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>3</td>
<td>Fiddler</td>
<td>3</td>
</tr>
<tr>
<td>5</td>
<td>1</td>
<td>Marci</td>
<td>1</td>
</tr>
<tr>
<td>6</td>
<td>5</td>
<td>Tails</td>
<td>2</td>
</tr>
</tbody>
</table>
<p>Here we have a table called AnimalTypes which contains 4 types of animals, and a table called Animals which lists out animals and what type they are.</p>
<p>Let&#8217;s say we want to write a program which will display all the animals in our animals table, as well as the Name of the Type of the animal, not the ID of the type. If an animal has an unknown type, we want to display &#8220;UNKNOWN.&#8221; Here is the <strong>bad</strong> process that we want to avoid.</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">*</span> <span style="color: #993333; font-weight: bold;">FROM</span> AnimalTypes
<span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">*</span> <span style="color: #993333; font-weight: bold;">FROM</span> Animals</pre></div></div>

<p>The <strong>bad</strong> program will then loop through all the animals and print out the Name field in the AnimalTypes results which corresponds to the given type ID. If one does not exist in the AnimalTypes results, the code could then print &#8220;UNKNOWN.&#8221;</p>
<p>It also might occur to you that you can write a query like this one, which would also be incorrect.</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span>
      <span style="color: #66cc66;">*</span>
<span style="color: #993333; font-weight: bold;">FROM</span>
      Animals<span style="color: #66cc66;">,</span> AnimalTypes
<span style="color: #993333; font-weight: bold;">WHERE</span>
      Animals<span style="color: #66cc66;">.</span>AnimalTypeID <span style="color: #66cc66;">=</span> AnimalTypes<span style="color: #66cc66;">.</span>AnimalTypeID</pre></div></div>

<p>This is the basis of an <strong>inner join</strong>. It can be written as an inner join query, but I wrote it in the manner above as an example. This query will return results, however you will only get animals who have a corresponding correct AnimalType. Our program wants to display all animals, regardless of whether or not they have a valid type selected. Using the tables from above, you would get these results:</p>
<table border="1" cellspacing="2" cellpadding="5" style = "border-collapse:collapse;">
<tbody>
<tr>
<th>AnimalID</th>
<th>AnimalTypeID</th>
<th>Name</th>
<th>Age</th>
<th>AnimalTypeID</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>Dusty</td>
<td>5</td>
<td>1</td>
<td>Dog</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>Jonesey</td>
<td>2</td>
<td>3</td>
<td>Turtle</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>Bonnie</td>
<td>1</td>
<td>2</td>
<td>Cat</td>
</tr>
<tr>
<td>4</td>
<td>3</td>
<td>Fiddler</td>
<td>3</td>
<td>3</td>
<td>Turtle</td>
</tr>
<tr>
<td>5</td>
<td>1</td>
<td>Marci</td>
<td>1</td>
<td>1</td>
<td>Dog</td>
</tr>
</tbody>
</table>
<p>If you notice, the animal <strong>Tails</strong> is missing from the list. This is because Tails&#8217; AnimalTypeID of 5 did not have a corresponding AnimalTypeID in the AnimalTypes table. In a query such as this, both values have to exist in both tables. This is not the case in our data, even though we want all animals to display.</p>
<p>What we need to use in this case is a <strong>left join</strong> or a <strong>left outer join</strong>.  The left join will take each record from the left-hand side of the join, and tie it to records on the right-hand side. If the tie does not exist in the right-hand table, then the left-hand fields will still exist in the results, with NULL values for the right-hand.</p>
<p>Here is the query using a left join.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> 
     <span style="color: #66cc66;">*</span> 
<span style="color: #993333; font-weight: bold;">FROM</span> 
     Animals
     <span style="color: #993333; font-weight: bold;">LEFT</span> <span style="color: #993333; font-weight: bold;">JOIN</span> AnimalTypes
          <span style="color: #993333; font-weight: bold;">ON</span> Animals<span style="color: #66cc66;">.</span>AnimalTypeID <span style="color: #66cc66;">=</span> AnimalTypes<span style="color: #66cc66;">.</span>AnimalTypeID</pre></td></tr></table></div>

<p>What you get here is every record from Animals, joined to the corresponding AnimalType record. In the case of Tails, we won&#8217;t get any AnimalType information.</p>
<table cellpadding = 5 cellspacing = 2 border = 1 style = 'border-collapse:collapse;'>
<tr>
<th>AnimalID</th>
<th>AnimalTypeID</th>
<th>Name</th>
<th>Age</th>
<th>AnimalTypeID</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>Dusty</td>
<td>5</td>
<td>1</td>
<td>Dog</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>Jonesey</td>
<td>2</td>
<td>3</td>
<td>Turtle</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>Bonnie</td>
<td>1</td>
<td>2</td>
<td>Cat</td>
</tr>
<tr>
<td>4</td>
<td>3</td>
<td>Fiddler</td>
<td>3</td>
<td>3</td>
<td>Turtle</td>
</tr>
<tr>
<td>5</td>
<td>1</td>
<td>Marci</td>
<td>1</td>
<td>1</td>
<td>Dog</td>
</tr>
<tr>
<td>6</td>
<td>5</td>
<td>Tails</td>
<td>2</td>
<td>NULL</td>
<td>NULL</td>
</tr>
</table>
<p>A very common use of this join is in financial transactions, where you might be missing the category of the transaction but still want the amount included.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2009/10/21/understanding-sql-joins-the-left-join/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Conditional Sums in SQL Queries</title>
		<link>http://www.daveandrews.org/2009/09/29/conditional-sums-in-sql-queries/</link>
		<comments>http://www.daveandrews.org/2009/09/29/conditional-sums-in-sql-queries/#comments</comments>
		<pubDate>Tue, 29 Sep 2009 17:06:36 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=132</guid>
		<description><![CDATA[One thing that you may encounter frequently is a situation where you want to count the records in a table which are of a certain type. You want to do this as efficiently as possible, instead of running a new count query for each type. Let&#8217;s use the below table for reference. Name Type Age [...]]]></description>
			<content:encoded><![CDATA[<p>One thing that you may encounter frequently is a situation where you want to count the records in a table which are of a certain type. You want to do this as efficiently as possible, instead of running a new count query for each type. Let&#8217;s use the below table for reference.</p>
<table border="1" cellspacing="5" cellpadding="5" border="1" style="border-collapse:collapse">
<tbody>
<tr>
<th>Name</th>
<th>Type</th>
<th>Age</th>
</tr>
<tr>
<td>Buffy</td>
<td>Dog</td>
<td>10</td>
</tr>
<tr>
<td>Dusty</td>
<td>Dog</td>
<td>13</td>
</tr>
<tr>
<td>Clyde</td>
<td>Dog</td>
<td>2</td>
</tr>
<tr>
<td>Bonnie</td>
<td>Cat</td>
<td>1</td>
</tr>
<tr>
<td>Milky</td>
<td>Ferret</td>
<td>1</td>
</tr>
</tbody>
</table>
<p>We have above a table of animals. How can we determine the count of each type of animal? The simplest (and most inefficient) is to run a count() query for each type of animal. This would mean we have 3 queries to run, as there are 3 types of animals.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;">declare @numdogs int
declare @numcats int
declare @numferrets int
&nbsp;
<span style="color: #993333; font-weight: bold;">SELECT</span> @numdogs <span style="color: #66cc66;">=</span> COUNT<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">*</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">FROM</span> animals <span style="color: #993333; font-weight: bold;">WHERE</span> type <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'Dog'</span>
<span style="color: #993333; font-weight: bold;">SELECT</span> @numcats <span style="color: #66cc66;">=</span> COUNT<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">*</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">FROM</span> animals <span style="color: #993333; font-weight: bold;">WHERE</span> type <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'Cat'</span>
<span style="color: #993333; font-weight: bold;">SELECT</span> @numferrets <span style="color: #66cc66;">=</span> COUNT<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">*</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">FROM</span> animals <span style="color: #993333; font-weight: bold;">WHERE</span> type <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'Ferret'</span>
&nbsp;
<span style="color: #993333; font-weight: bold;">SELECT</span> @numdogs <span style="color: #993333; font-weight: bold;">AS</span> NumDogs<span style="color: #66cc66;">,</span> @numcats <span style="color: #993333; font-weight: bold;">AS</span> NumCats<span style="color: #66cc66;">,</span> @numferrets <span style="color: #993333; font-weight: bold;">AS</span> NumFerrets</pre></td></tr></table></div>

<p>We will get results from that query like this.</p>
<table border="1" cellspacing="5" cellpadding="5" border="1" style="border-collapse:collapse">
<tbody>
<tr>
<th>NumDogs</th>
<th>NumCats</th>
<th>NumFerrets</th>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
<p>As you can imagine, this is terribly inefficient. A good answer in this case is to use a &#8220;conditional&#8221; sum in the SQL query. So rather than running COUNT(*) we will be running SUM(&#8230;).  We will combine the SUM() call with a CASE statement, so that it counts correctly. This is the trick I hope to teach you. You can place CASE &#8230; END statements inside of aggregate functions.</p>
<p>Throw away all of our temporary variables, the 4 select statements involved, and let&#8217;s replace them with this single select.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> 
	SUM<span style="color: #66cc66;">&#40;</span>CASE WHEN type<span style="color: #66cc66;">=</span><span style="color: #ff0000;">'Dog'</span> then <span style="color: #cc66cc;">1</span> else <span style="color: #cc66cc;">0</span> end<span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">AS</span> NumDogs<span style="color: #66cc66;">,</span>
	SUM<span style="color: #66cc66;">&#40;</span>CASE WHEN type<span style="color: #66cc66;">=</span><span style="color: #ff0000;">'Cat'</span> then <span style="color: #cc66cc;">1</span> else <span style="color: #cc66cc;">0</span> end<span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">AS</span> NumCats<span style="color: #66cc66;">,</span>
	SUM<span style="color: #66cc66;">&#40;</span>CASE WHEN type<span style="color: #66cc66;">=</span><span style="color: #ff0000;">'Ferret'</span> then <span style="color: #cc66cc;">1</span> else <span style="color: #cc66cc;">0</span> end<span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">AS</span> NumFerrets
<span style="color: #993333; font-weight: bold;">FROM</span> 
	animals</pre></td></tr></table></div>

<p>We get these results:</p>
<table border="1" cellspacing="5" cellpadding="5" style="border-collapse:collapse">
<tbody>
<tr>
<th>NumDogs</th>
<th>NumCats</th>
<th>NumFerrets</th>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
<p>Which is exactly what we got previously, but using a much more efficient method. The trick was to insert a CASE &#8230; END statement inside the SUM. The case will return a 1 when the type is the type we are looking for, and a 0 otherwise. The sum will then execute to add up all of those 0s and 1s. A 0 will not add anything, so we will effectively end up counting the values which match the type we are looking for.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2009/09/29/conditional-sums-in-sql-queries/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
