1

I have 5 different columns with over 100 rows each having an assortment of numbers.

I have been able to count all values from column 1 that equal 3

I want to be able to count all the number 3s from all 5 different columns and add them

$countquery = "SELECT COUNT(*) FROM PowerBall WHERE W1=3";
$countresult = mysql_query($countquery) or die(mysql_error());

while($countrow = mysql_fetch_array($countresult)) {
    echo "<br />";
    echo "There are ". $countrow['COUNT(*)']."-3s";
}
1

2 Answers 2

4

You can use an aggregate function with a CASE expression to get the total number of 3 values in all of your columns.

Select
  sum(case when col1 = 3 then 1 else 0 end) TotalCol1,
  sum(case when col2 = 3 then 1 else 0 end) TotalCol2,
  sum(case when col3 = 3 then 1 else 0 end) TotalCol3,
  sum(case when col4 = 3 then 1 else 0 end) TotalCol4,
  sum(case when col5 = 3 then 1 else 0 end) TotalCol5
from PowerBall

If you want this in one column, then you can use:

select TotalCol1 + TotalCol2 + TotalCol3 + TotalCol4 + TotalCol5
from
(
  Select
    sum(case when col1 = 3 then 1 else 0 end) TotalCol1,
    sum(case when col2 = 3 then 1 else 0 end) TotalCol2,
    sum(case when col3 = 3 then 1 else 0 end) TotalCol3,
    sum(case when col4 = 3 then 1 else 0 end) TotalCol4,
    sum(case when col5 = 3 then 1 else 0 end) TotalCol5
  from PowerBall
) src

Or even:

select sum(Total)
from
(
  Select count(col1) Total
  from PowerBall
  where col1 = 3
  union all
  Select count(col2)
  from PowerBall
  where col2 = 3
  union all
  Select count(col3)
  from PowerBall
  where col3 = 3
  union all
  Select count(col4)
  from PowerBall
  where col4 = 3
  union all
  Select count(col5)
  from PowerBall
  where col5 = 3
) src
Sign up to request clarification or add additional context in comments.

5 Comments

you don't need a CASE statement, SUM(COL1=3) will suffice since it's already a boolean and will evaluate to either 1 or 0.
@KevinNelson I use CASE because it is ANSI standard SQL. The SUM(COl1 =3) is MySQL specific syntax. :)
Whats the TotalCol1 does it calculate or is it a variable
@inVINCEable Those are the alias names for each of the columns created. The as is optional.
TotalCol1 references the SUM calculation from the derived query.
1
SELECT SUM(CASE WHEN COL1 = 3 THEN 1 ELSE 0 END) AS 'Col1',
SUM(CASE WHEN COL1 = 3 THEN 1 ELSE 0 END) AS 'Col2',
....
 FROM PowerBall WHERE W1 is not null

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.