Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Column Conditional Count SQL

I am trying to count distinct entries in 4 separate columns in a row and then total the results.

For instance the table headers look similar to this:

ID       Col1    Col2    Col3    Col4

Each column (save ID) can have a text value W, X, Y, or Z. Columns can have the same value.

What I am trying to do is figure a method for counting each entries in the columns, but only count W, X, Y, and Z once per row. So if:

ID       Col1    Col2    Col3    Col4
          X        X       Y
          Y        W       X
          Z        Y       Y

The result table would be:

    Value    Count
      W        1
      X        2
      Y        3
      Z        1

Any help would be greatly appreciated.

like image 393
dooms13 Avatar asked May 31 '26 08:05

dooms13


1 Answers

Perhaps I'm missing something, but would this be as simple as:

Select Val, Count(*)
From    (
        Select Id, Col1 As Val From Table1
        Union Select Id, Col2 From Table1
        Union Select Id, Col3 From Table1
        Union Select Id, Col4 From Table1
        ) As Z
Where Z.Val Is Not Null
Group BY Z.Val

There is no reason to use Distinct and Union together as Union will make the results distinct. Because of that, we need to include the unique value for each row (Id).

SQL Fiddle (This uses SQL Server but the same syntax will work in MS Access)

like image 112
Thomas Avatar answered Jun 02 '26 06:06

Thomas