|
|
| Thursday, 11/20/2008 | |
|
|
|
|
|
Waztech Internet Services Tech Support
As a service to the ASP Community and SQL Programmers, we have posted this sample SQL Snippet. SQL SnippetsCounting Records from 3 tables, 2 of which are joined together by a common data element.Goal:We want to display a list of Newsletter Topics, and show how many active subscribers there are for each topic.
Table Structure:You have 3 tables. Topics – a list of topics for newsletters Subscribers – a list of subscribers to newsletters Subscribers_Topics - a table to join subscribers to Topics Each table has data columns as follows: Topics
Subscribers
Subscribers_Topics
SQL Query:SELECT NT.ID, NT.Name, Count(NST.Subscriber_ID) AS Subscribers FROM Topics as NT INNER JOIN ( Subscribers as NS INNER JOIN Subscribers_Topics AS NST ON NS.ID = NST.Subscriber_ID ) ON NT.ID = NST.Topic_ID GROUP BY NT.ID, NT.Name, NS.Subscribe, NT.List_Position HAVING ( (NS.Subscribe)=True ) ORDER BY NT.List_Position Results:
Explanation:An INNER JOIN can only join 2 tables together. We need to join 3 tables together So we must “nest” the first join between 2 tables inside the first inner join. INNER JOIN ( Subscribers as NS INNER JOIN Subscribers_Topics AS NST ON NS.ID = NST.Subscriber_ID ) ON NT.ID = NST.Topic_ID We use GROUP BY to combine rows that have the same field values, so we can get a count of them. Without GROUP BY our results list would look like this:
We use HAVING as a filter to limit the records that are returned. This is the same theory as using the WHERE operator, but since we are using GROUP BY, we need to use the HAVING function to limit the results. Thank you for hosting with Waztech Internet Services
|
![]() |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||
|
|
||
| © 2008 Waztech | Request Business Card | |