July 19, 2011

SQL Server: Distinct Count across Multiple Tables

One of my clients had a SQL Server database with an email column repeated across multiple tables. He wanted two queries – all email’s that are not repeated across the table, i.e. distinct ones as well as a count of the email addresses across multiple tables in the database.

I gave him a query that will help him out to do a count across multiple tables as well as list all distinct emails. Let us consider the following sample data

sql-distinct-count-multiple-tables

Now to do a count of email across multiple tables, use the following query:

SELECT tt.email, COUNT(tt.email) as EmailCount
FROM (  SELECT email FROM @t
        UNION ALL
        SELECT email FROM @t1) tt
GROUP BY tt.email


OUTPUT


image

Similarly to list all distinct email addresses, i.e the ones not repeated, use the HAVING clause (there are other ways too)

SELECT tt.email, COUNT(tt.email) as EmailCount
FROM (  SELECT email FROM @t
        UNION ALL
        SELECT email FROM @t1) tt
GROUP BY tt.email
HAVING COUNT(tt.email) = 1


image


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

No comments: