Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Count distinct values on sevaral fields

Count distinct values on sevaral fields

Count distinct values on sevaral fields

Hi, I have a sort of stupid table structure on the project I inherited. It's a list of what work was performed that uses codes like this:

CustomerID | Date | Code1 | Code2 | Code3 | Code4

I want to know all work that was performed for a certain period and thus need to count the distinct codes on codes 1-4.

Say I have the test data:

1 | today | AA | AB | AC | Null
2 | today | AC | BB | Null | Null

I want to get the following:

AA | 1
AB | 1
AC | 2
BB | 1

The table is pretty huge so I need an effective query... Any hints?


RE: Count distinct values on sevaral fields


     , COUNT(*) AS daCount
  FROM ( SELECT Code1 AS daCode
           FROM daTable
          WHERE Code1 IS NOT NULL
         UNION ALL
         SELECT Code2
           FROM daTable
          WHERE Code2 IS NOT NULL
         UNION ALL
         SELECT Code3
           FROM daTable
          WHERE Code3 IS NOT NULL
         UNION ALL
         SELECT Code4
           FROM daTable
          WHERE Code4 IS NOT NULL
       ) AS d
    BY daCode

r937.com | rudy.ca
Buy my new book Simply SQL from Amazon

RE: Count distinct values on sevaral fields

I think I did it! Check this out:


select Work.Code, count(*) from (
select Code1 as Code from table1
union all
select Code2 as Code from table1
) as Work
where Work.Code is not null
group by Work.Code

What do you think?


RE: Count distinct values on sevaral fields

LOL nice coincidence! Thanks man.


Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close