Ask the Expert

COUNT DISTINCT in two different columns

I have a question quite similar to the one in Comparing two tables (20 January 2003).

I have a table that has two columns - author name (authname) and first author name (fauthname). The pk is authId. I need to compare the data in these two fields, and if any data in fauthname already exists in authname then I need it to be temporarily deleted, and any data not currently existing in authname should be added to authname. My goal is to be able to count the total number of authors. Am I making this harder than it is?


    Requires Free Membership to View

Yes. If all you want is to count the number of distinct authors, you are.

There are many ways to do it. Here's the easiest:

select count(*)
  from (
       select authname
         from yourtable
     union
       select fauthname
         from yourtable
       )

UNION removes duplicates (UNION ALL would preserve them). Then just take the count.


This was first published in August 2003

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.