Reputation: 2206
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";
}
Upvotes: 1
Views: 83
Reputation: 247690
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
Upvotes: 4
Reputation: 4190
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
Upvotes: 1