February 8, 2008 at 2:25 pm
I have an account and contact table. An account may have 1 or more contacts. How do I identify accounts that have ONLY 1 contact? I need to show both the account and the contact.
Thanks!
February 8, 2008 at 4:23 pm
This approach should work. Keep in mind that from your description, I have no idea what your table DDL looks like. This is a wild stab in the dark. You'll have to take this approach and fit it to your tables but it should be close.
DECLARE @Contacts TABLE (ContactID int, Contact varchar(20))
INSERT INTO @Contacts
SELECT 1, 'Bob' UNION ALL
SELECT 2, 'Nick' UNION ALL
SELECT 3, 'SALLY' UNION ALL
SELECT 4, 'Fred'
DECLARE @Accounts TABLE (AccountID int,
ContactID int,
Value varchar(20))
INSERT INTO @Accounts
SELECT 1, 1, 'Act 1, 2 Contacts' UNION ALL
SELECT 1, 2, 'Act 1, 2 Contact' UNION ALL
SELECT 2, 4, 'Act 2, 1 Contact'
SELECT *
FROM @Accounts a1
INNER JOIN (
SELECT AccountID
FROM @Accounts
GROUP BY AccountID
HAVING COUNT(*) = 1
) a2
ON a1.AccountID = a2.AccountID
February 8, 2008 at 5:07 pm
That should do it... nicely done, John.
--Jeff Moden
Change is inevitable... Change for the better is not.
February 11, 2008 at 8:42 am
Thank you very much - this was just what I was looking for!
Barbara
February 11, 2008 at 9:13 am
No problem. The key to this one is the derived table. If you're not real familiar with derived tables, I suggest searching SSC and reading up on them. There's also info in BOL. Understanding how and when to use derived tables can greatly simplify your code and they can be a great tool for query tuning for helping with replacing cursors or correlated subqueries.
Viewing 5 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply